Wednesday, December 19, 2018

[LeetCode]Two Sum


很常见和基础的题目,输入不一定是sorted的,用hashset解决。时间空间复杂度均为O(N),代码如下:


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 {};
}
};
view raw Two Sum.cpp hosted with ❤ by GitHub

No comments:

Post a Comment