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
began to write an O (n^2) solution, timed out. An O (n) solution was seen on the internet, using a hash map. Only iterate through the array, the number of traversed by the existence of a hash map, the value as the key, the ordinal I as value, so that you can achieve a fast lookup of the traversed value. For example, the current traversal to the K element, and then go to hash map to find Target-nums[k] This key exists, if there is printing two coordinates, if there is no current key-value to the hash map, of course, the premise of saving is that this value is the first occurrence, If you've already seen it before, skip to the next element without saving it. In C + +, of course, the map is implemented, but the map in C + + is implemented by default, with an average lookup complexity of O (Logn). The last time complexity is O (NLOGN)
Class Solution {public: vector<int> twosum (vector<int>& nums, int target) { std::vector< int> result; if (nums.size () = = 0) return result; int index1 = 0, index2 = 0; Map<int, Int> appeared; for (int i = 0; i < nums.size (); i++) { if (Appeared.count (Target-nums[i])) { Result.push_back (appeared[target -Nums[i]] + 1); Result.push_back (i + 1); return result; } if (!appeared.count (Nums[i])) appeared[nums[i]] = i; }} ;
[Leetcode] The Sum of