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 not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解题思路一
先对数组排序,然后用left和right指针找到目标值,最后找到目标值的位置即可。
C++代码如下:
1 #include<vector> 2 #include <algorithm> 3 using namespace std; 4 class Solution { 5 public: 6 vector<int> twoSum(vector<int> &numbers, int target) { 7 int left = 0, right = numbers.size() - 1, sum; 8 vector<int> sorted(numbers); 9 sort(sorted.begin(), sorted.end()); 10 vector<int> index; 11 while (left < right) { 12 sum = sorted[left] + sorted[right]; 13 if (sum == target) { 14 for (int i = 0; i < numbers.size(); i++) { 15 if (numbers[i] == sorted[left]) 16 index.push_back(i + 1); 17 else if (numbers[i] == sorted[right]) 18 index.push_back(i + 1); 19 if (index.size() == 2) 20 return index; 21 } 22 } 23 else if (sum > target) 24 right--; 25 else 26 left++; 27 } 28 } 29 };
解题思路二
由于图的遍历所需时间开销比较固定,因此可以使用HashMap,以数组的内容为key,以数组下标为Value,这样时间复杂度为O(n)。
因此,第一步:将数组元素存入HashMap里面;第二步:将对于numbers[]的每个值,用target-numbers[i]在图中进行遍历,如果发现存在这样的值,并且这样的值不是numbers[i]对应的节点本身,那么,遍历结束。
Java代码如下:
public class Solution { static public int[] twoSum(int[] numbers, int target) { int[] a={0,0}; HashMap<Integer,Integer> map=new HashMap<Integer,Integer>(); for(int i=0;i<numbers.length;i++){ map.put(numbers[i], i); } for(int i=0;i<numbers.length;i++){ int gap=target-numbers[i]; if((map.get(gap)!=null)&&map.get(gap)!=i){ a[0]=i+1; a[1]=map.get(gap)+1; break; } } return a; } }
C++实现如下:
1 #include<vector> 2 #include<unordered_map> 3 class Solution { 4 private: 5 unordered_map<int, int> numMap; 6 vector<int> res; 7 public: 8 vector<int> twoSum(vector<int> &numbers, int target) { 9 for (int i = 0; i < numbers.size(); i++) 10 numMap.insert(unordered_map<int, int>::value_type(numbers[i], i)); 11 for (int i = 0; i < numbers.size(); i++) { 12 unordered_map < int, int >::iterator iter; 13 int gap = target - numbers[i]; 14 iter = numMap.find(gap); 15 if (iter != numMap.end()&&numMap[gap]!=i) { 16 res.push_back(i+1); 17 int num2 = numMap[gap]+1; 18 if(num2>i+1) 19 res.push_back(num2); 20 else 21 res.insert(res.begin(),num2); 22 return res; 23 } 24 } 25 } 26 };