很常见和基础的题目,输入不一定是sorted的,用hashset解决。时间空间复杂度均为O(N),代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<int> twoSum(vector<int>& nums, int target) { | |
unordered_map<int, int> map; | |
int len = nums.size(); | |
for(int i = 0; i < len; ++i) | |
{ | |
int toFind = target - nums[i]; | |
if(map.find(toFind) != map.end()) | |
return {map[toFind], i}; | |
map[nums[i]] = i; | |
} | |
return {}; | |
} | |
}; |
No comments:
Post a Comment