HF_Cherish

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1. Question

给一整数数组,找两个数,使其和正好是给定值。函数 twoSum应当返回两个数的索引,且index1小于index2。索引不是从0开始的。

假设每个输入都正好有一个解。

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

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

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

2. Solution

最优方案时间复杂度O(n)

2.1 O(n2) solution

用两个循环遍历所有数对,找到符合要求的。

2.2 O(nlogn) solution

方案一:采用二叉搜索

  1. 数组按升序排序(采用map存储数组值和索引)
  2. 遍历数组,假设每个值是两个数的其中一个值,采用二叉搜索查找另一个值。
 1 import java.util.ArrayList;
 2 import java.util.Arrays;
 3 import java.util.Collections;
 4 import java.util.Comparator;
 5 import java.util.Map.Entry;
 6 import java.util.HashMap;
 7 
 8 public class Solution {
 9     public int[] twoSum( int[] numbers, int target ){
10         HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
11         for( int k=0; k<numbers.length; k++ )
12             map.put(k,numbers[k]);
13         //sort by num value, nlog(n) time
14         ArrayList<Entry<Integer,Integer>> num = new ArrayList<Entry<Integer,Integer>>( map.entrySet() );
15         Comparator<Entry<Integer,Integer>> comp =  new Comparator<Entry<Integer,Integer>>(){
16             public int compare( Entry<Integer,Integer> e1, Entry<Integer,Integer> e2 ){
17                 return e1.getValue() - e2.getValue();
18             }
19         };
20         Collections.sort( num, comp);
21         
22         //get the sorted array, n time
23         int[] sorted = new int[numbers.length];
24         for( int k=0; k<numbers.length; k++ )
25             sorted[k] = num.get(k).getValue().intValue();
26         
27         //find twoSum from the sorted array, using binary search, nlog(n) time
28         int mid = target/2;
29         if( sorted[numbers.length-1]< mid ) return null;
30         int i;
31         for( i=0; sorted[i]<mid; i++ );
32         if( sorted[i] > mid )
33             i--;
34         int index1;
35         int index2;
36         for( index1=0; index1<=i; index1++ ){
37             index2 = Arrays.binarySearch( sorted, i+1, sorted.length, target - sorted[index1] );
38             if( index2 >0 ){
39                 index1 = num.get(index1).getKey()+1;
40                 index2 = num.get(index2).getKey()+1;
41                 if( index1 < index2 )
42                     return new int[] { index1, index2 };
43                 else
44                     return new int[] { index2, index1 };
45             }
46         }
47         return null;
48     }
49 }
binary-search

 

方案二:采用双指针

  1. 数组按升序排序(注意索引)
  2. 采用双指针,一个指针head指向数组头,一个指针tail指向数组尾。判断num[head]+num[tail]:
    1. 如果和小与给定值,head++(向和增大的方向移动指针)
    2. 如果和大于给定值,tail--(向和减小的方向移动指针)
    3. 如果和等于给定值,返回相应的索引值,按要求返回。
 1 import java.util.Arrays;
 2 
 3 
 4 public class Solution {
 5         public int[] twoSum( int[] numbers, int target ){
 6         //if and only if there are two same numbers which sum to target, for the result, there is no duplicates in the array.
 7         int[] sNum = numbers.clone();
 8         Arrays.sort(sNum);
 9         
10         int mid = target / 2;
11         if( sNum[sNum.length-1] < mid )    return null;
12         
13         int index1 = 0;
14         int index2 = sNum.length-1;
15         while( index1 < index2 ){
16             int sum = sNum[index1] + sNum[index2];
17             if( sum==target ){
18                 for( int k=0; k<numbers.length; k++ ){
19                     if( sNum[index1] == numbers[k] ){
20                         index1 = k;
21                         break;
22                     }                    
23                 }
24                 for( int k = numbers.length-1; k>=0;  k-- ){
25                     if( sNum[index2] == numbers[k] ){
26                         index2 = k;
27                         break;
28                     }
29                 }
30                 if( index1 > index2 ){
31                     int temp = index1;
32                     index1 = index2;
33                     index2 = temp;
34                 }
35                 return new int[] { index1+1, index2+1 };
36             }
37             if( sum < target )
38                 index1++;
39             else
40                 index2--;
41         }
42         
43         return null;
44     }
45 }
two-pointers

 

2.3 O(n) solution

采用map保存数组,数值为键,索引为值。遍历数组,如果不在map中,加入map。考察map中是否存在满足num[i]要求的数。

该方法对数组中的每个数都找是否有符合要求的另一个数,因此不会有遗漏(这是最符合人的思路的方法)。且由于采用map,找的时间为常数时间,从而算法时间复杂度O(n).

 1 import java.util.Hashtable;
 2 
 3 
 4 public class Solution {
 5     //when using map structure, we don't need to sort the array
 6     public int[] twoSum( int[] numbers, int target ){
 7         Hashtable< Integer, Integer > num = new Hashtable< Integer, Integer >();
 8         for( int i=0; i< numbers.length; i++ ){
 9             if( num.get( numbers[i]) == null )
10                 num.put(numbers[i], i);
11             Integer j = num.get( target - numbers[i]);
12             if( j!=null && j < i )
13                 return new int[] { j.intValue()+1, i+1 };
14         }
15         return null;
16     }
17 }
map

 

posted on 2015-06-10 20:56  HF_Cherish  阅读(220)  评论(0编辑  收藏  举报