Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
暴力解法就不列出来了,上一个比较好理解且高效的方法:
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) 4 { 5 int n = nums.size(); 6 unordered_map<int, int> hash; 7 vector<int> res; 8 9 for (int i = 0; i < n; ++i) 10 { 11 int solu = target - nums[i]; 12 13 if (hash.find(solu) != hash.end()) 14 { 15 //Find! 16 res.push_back(i); 17 res.push_back(hash[solu]); 18 return res; 19 } 20 21 //Not Find 22 hash[nums[i]] = i; 23 } 24 } 25 };

浙公网安备 33010602011771号