【LeetCode 1】两数之和
描述
【题解】
用个map的话就是O(N)级别的了。【代码】
class Solution {
public:
unordered_map<int,int> mymap;
vector<int> twoSum(vector<int>& nums, int target) {
int len = nums.size();
vector<int> ans;
ans.resize(2);
for (int i = 0;i < len;i++){
int x = nums[i];
if (mymap.find(target-x)!=mymap.end()){
ans[0] = mymap[target-x];
ans[1] = i;
return ans;
}
mymap[nums[i]] = i;
}
return ans;
}
};