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 mus T is less than INDEX2. Please note that your returned answers (both Index1 and Index2) is not zero-based.
Notice
You may assume this each input would has exactly one solution
Example
numbers= [2, 7, 11, 15]
, target=9
Return[1, 2]
Challenge
Either of the following solutions is acceptable:
- O (n) Space, O (nlogn) time
- O (n) Space, O (n) time
Public classSolution {/** @param numbers:an array of Integer * @param target:target = numbers[index1] + numbers[index2] * @re Turn: [index1 + 1, Index2 + 1] (Index1 < INDEX2)*/ Public int[] Twosum (int[] numbers,inttarget) { //Write your code here int[] res =New int[2]; HashMap<integer, integer> map =NewHashmap<integer, integer>(); for(inti = 0; i < numbers.length; i++){ if(!Map.containskey (Numbers[i])) {Map.put (target-Numbers[i], i); } Else{ intin1 = Map.get (numbers[i]) + 1; intin2 = i + 1; res[0] =in1; res[1] =in2; returnRes; } } returnRes; }}
Lintcode-medium-two Sum