LeetCode 1 Two Sum

原题如下:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 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.

最直接的方法是两层循环遍历数组,对数组中所有元素一一相加并比对结果,时间复杂度是O(n^2)。代码如下:

 1     public int[] twoSum1(final int[] numbers, int target) {
 2         for (int i = 0; i < numbers.length; i++) {
 3             for (int j = i+1; j < numbers.length; j++) {
 4                 int sum = numbers[i] + numbers[j];
 5                 if(sum == target){
 6                     return new int[]{i,j};
 7                 }
 8             }
 9         }
10         return null;
11     }

优化之后时间复杂度可以降为O(nlogn),具体方法是先对数组进行排序(nlogn),然后分别使用两个指针从数组头和数组尾开始查找(n),利用数组有序的特性可以在O(n)的时间复杂度内完成检索。代码如下:

 1     public int[] twoSum2(final int[] numbers, int target) {
 2         List<Integer> indexes = new ArrayList<Integer>();
 3         for(int i = 0; i < numbers.length ; i++){
 4             indexes.add(i);
 5         }
 6         Collections.sort(indexes, new Comparator<Integer>(){
 7             @Override
 8             public int compare(Integer o1, Integer o2) {
 9                 return numbers[o1]-numbers[o2];
10             }
11         });
12         int i=0,j=numbers.length-1;
13         while(i < j){
14             int sum = numbers[indexes.get(i)] + numbers[indexes.get(j)];
15             if(sum == target){
16                 break;
17             }else if(sum < target){
18                 i++;
19             }else{
20                 j--;
21             }
22         }
23         if(i < j){
24             int i1 = indexes.get(i);
25             int i2 = indexes.get(j);
26             return i1< i2? new int[]{i1,i2}:new int[]{i2,i1};
27         }
28         return null;
29     }

参考源码:https://github.com/pkufork/Martians/blob/master/src/main/java/com/pkufork/martians/leetcode/L1_TwoSum.java

原文地址:https://www.cnblogs.com/pkufork/p/ds_leetcode_1.html