Topic:
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
Tag:
Array; Hash Table
Experience:
Ah haha, this problem once success, although the version is different from the following, but the idea is the same.
This problem is very clever with the map, because it is to find two numbers together can be target, so encountered a number, you know it should be with whom to make up the right, although do not know whether the number can be found in the array exists in or exist somewhere. Make a map of <number, Index>, and record where each number appears. Check the numbers one after the other to see if the number he's trying to make is already there.
P.S. My map has the number that I want to find directly. For example Target=9, now in position 0 met 2, then I will save a map[9-2]=0, and then check the time can go directly to the keys to find whether there is 7.
1 classSolution {2 Public:3vector<int> Twosum (vector<int> &numbers,inttarget) {4 intn =numbers.size ();5vector<int>result;6map<int,int>index;7 for(inti =0; I < n; i++) {8 if(Index.count (numbers[i])! =0) {9 //if existsTenResult.push_back (Index[numbers[i]) +1); OneResult.push_back (i +1); A Break; - } -Index[target-numbers[i]] =i; the } - returnresult; - } -};
[Leetcode] Both Sum (c + +)