🔖
Leetcode 配列/文字列 二重ループ
Two Sum
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map<int, int> dic;
for(int i = 0; i < nums.size(); i++){
if (dic.contains(target-nums[i])){
return {dic[target - nums[i]], i};
}
dic[nums[i]] = i;
}
return {};
}
};
time complexity: O(n)
space complexity: O(n) The extra space required depends on the number of items stored in the hash table.
Discussion