The original question is as follows:
Given an array of integers, return indices of the both numbers such that they add-to a specific target.
You may assume this each input would has exactly one solution.
Example:
Given nums = [2, 7, one, 2], target = 9,because nums[0] + nums[1] = + 7 = 9,return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
The most straightforward method is to iterate through the array in a two-tier loop, adding and n^2 all element one by one in a set, and the time complexity is O (-). The code is as follows:
1 Public int[] TWOSUM1 (Final int[] numbers,inttarget) {2 for(inti = 0; i < numbers.length; i++) {3 for(intj = i+1; J < Numbers.length; J + +) {4 intsum = numbers[i] +Numbers[j];5 if(Sum = =target) {6 return New int[]{i,j};7 }8 }9 }Ten return NULL; One}
After optimization, the time complexity can be reduced to O (Nlogn), the method is to sort the array (NLOGN), and then use two pointers to find (n) from the arrays head and the end of the group, using an array of ordered features can be in O (n) time complexity to complete the search. The code is as follows:
1 Public int[] twoSum2 (Final int[] numbers,inttarget) {2list<integer> indexes =NewArraylist<integer>();3 for(inti = 0; i < numbers.length; i++){4 Indexes.add (i);5 }6Collections.sort (Indexes,NewComparator<integer>(){7 @Override8 Public intCompare (integer O1, integer o2) {9 returnnumbers[o1]-Numbers[o2];Ten } One }); A intI=0,j=numbers.length-1; - while(I <j) { - intsum = Numbers[indexes.get (i)] +Numbers[indexes.get (j)]; the if(Sum = =target) { - Break; -}Else if(Sum <target) { -i++; +}Else{ -j--; + } A } at if(I <j) { - intI1 =Indexes.get (i); - intI2 =Indexes.get (j); - returni1< i2?New int[]{i1,i2}:New int[]{i2,i1}; - } - return NULL; in}
Reference Source: Https://github.com/pkufork/Martians/blob/master/src/main/java/com/pkufork/martians/leetcode/TwoSum1.java
Leetcode 1-two Sum