1、twoSum
关键:Hash
unordered_map<int, int> map;
map.count(key) 判断key对应value的个数
map[key] = value 插入{key,value}
复杂度为O(n)
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 unordered_map<int, int> hash; 5 vector<int> res; 6 for(int i=0; i<nums.size(); i++){ 7 int y = target - nums[i]; 8 if(hash.count(y)){ 9 res.push_back(i); 10 res.push_back(hash[y]); 11 } 12 hash[nums[i]]=i; 13 } 14 return res; 15 } 16 };

浙公网安备 33010602011771号