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 };
原文地址:https://www.cnblogs.com/amazingzoe/p/5797193.html