Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum
should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are NOTzero-based.
Notice
You may assume that each input would have exactly one solution
Example
numbers=[2, 7, 11, 15]
, target=9
return [1, 2]
Analyse: Be aware of that one element could appear more than once. Map each element into an array.
Runtime: 10ms
1 class Solution { 2 public: 3 /* 4 * @param numbers : An array of Integer 5 * @param target : target = numbers[index1] + numbers[index2] 6 * @return : [index1+1, index2+1] (index1 < index2) 7 */ 8 vector<int> twoSum(vector<int> &nums, int target) { 9 // write your code here 10 11 // use a hash map to store array information 12 // the key is element in nums, value is the index of that element 13 unordered_map<int, vector<int> > um; 14 for (int i = 0; i < nums.size(); i++) { 15 um[nums[i]].push_back(i); 16 } 17 18 // scan the array and find if (target - element) in the hash map 19 vector<int> result; 20 for (int i = 0; i < nums.size(); i++) { 21 if (um.find(target - nums[i]) != um.end()) { 22 // a value appears more than once and happens to equal to half of target 23 if (nums[i] == target - nums[i]) { 24 result.push_back(um[nums[i]][0] + 1); 25 result.push_back(um[nums[i]][1] + 1); 26 } 27 else { 28 int index1 = um[nums[i]][0], index2 = um[target - nums[i]][0]; 29 result.push_back(min(index1, index2) + 1); 30 result.push_back(max(index1, index2) + 1); 31 } 32 break; 33 } 34 } 35 return result; 36 } 37 };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步