Title Description:
Given an array of integers, find the numbers such that they add up to a specific target number.
The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.
You may assume this each input would has exactly one solution.
Input:numbers={2, 7, one, A, target=9
Output:index1=1, index2=2
Thinking:
1. First did not notice examining, thought that the array is sorted, then uses two pointers, one after the other, until the target and the pointer is found
Vector<int> twosum (vector<int> &numbers, int target) { int start = 0; int tail = numbers.size ()-1; vector<int> result; while (Start<tail) { if (Numbers[start] + Numbers[tail] <target) { start + +; } else if (Numbers[start] + Numbers[tail] > target) { tail--; } else{ result.push_back (start); Result.push_back (tail); return result;}} }
After submission, find runtime Error
2. Then consider the method of violence, Time complexity O (n^2)
Vector<int> twosum (vector<int> &numbers, int target) { vector<int> result; for (int i =0;i<numbers.size (), i++) {for (int j=i+1;j<numbers.size (); j + +) { if (Numbers[i] + numbers[j) = = Target) { result.push_back (i+1); Result.push_back (j+1); return result;}}}
Discover time Limit exceeded.
3. The search for a faster method, the online reference, found the need to Hashtable, using the STL map to achieve.
Vector<int> twosum (vector<int> &numbers, int target) { vector<int> result; Map<int,int> Map_res; for (int i =0;i<numbers.size (); i++) { int temp = target-numbers[i]; if (Map_res[temp]) { result.push_back (map_res[temp]+1); Result.push_back (i+1); } map_res[numbers[i]]=i; } return result; }
4. Found the result is still wrong, Runtime error, the error example is [0,4,3,0], 0, found that the original value of Map_res[0] corresponds to 0, changed the method, using Map_res.count (temp), finally AC
Vector<int> twosum (vector<int> &numbers, int target) { vector<int> result; Map<int,int> Map_res; for (int i =0;i<numbers.size (); i++) { int temp = target-numbers[i]; if (Map_res.count (temp)) { result.push_back (map_res[temp]+1); Result.push_back (i+1); } map_res[numbers[i]]=i; } return result; }
Leetcode 1:two Sum