LeetCode @ Two Sum D2F5

来源:互联网 发布:世界征服者3 数据同步 编辑:程序博客网 时间:2024/06/07 06:44

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

 (来源于:http://blog.csdn.net/linhuanmars/article/details/19711387

方法1:brute force时间复杂度为O(n^2), 对每一对pair两两比较。OJ超时!

public class Demo {    public static int[] twoSum(int[] numbers, int target) {        int[] res=new int[2];        for(int i=0;i<numbers.length-1;i++){            for(int j=i+1;j<numbers.length;j++){                if(numbers[i]+numbers[j]==target){                    res[0]=i;                    res[1]=j;                }            }        }        return res;    }public static void main(String[] args){ int[] numbers={2, 7, 11, 15}; int target=9; int[] res=twoSum(numbers,target);System.out.println(res[0]+" "+res[1]);}}

方法2:哈希表,存储每个数的下标。时间复杂度为O(n),同时空间复杂度也是O(n)。

public class Solution {    public int[] twoSum(int[] numbers, int target) {        if(numbers==null || numbers.length<2)            return null;        int[] res=new int[2];        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();         for(int i=0;i<numbers.length;i++){            if(map.containsKey(target-numbers[i])){//for的遍历已经获取了第一个数,所以if关注于(target减去第一个数)                res[0]=map.get(target-numbers[i])+1;//get(),获取map的value【注意1】                res[1]=i+1;                return res;            }            map.put(numbers[i],i);        }        return null;    }}

【注意1】HashMap存取无续,所以res[]对应结果不一致。(是这样么,有待验证)

【注意2】把i数组的值存入Key,index存入Value。每个chain看作成若干EntryNode组成,每个Node有{int Key,int Value,EntryNode next}两个值和一个引用组成。

【后记】有个问题:[3,2,4],target=6;那么3+3=6是个问题么?

【后记】对HashMap还不理解深入,我的理解为地址值直接由底层算出hashVal(其实就是地址)得知,在O(1)时间可以获得;对比于array,需要遍历,只能在O(n)时间内获得。

方法3:先排序,然后左右夹逼 (来源于:http://blog.csdn.net/linhuanmars/article/details/19711387)

先对数组进行排序,然后使用夹逼的方法找出pair。因为数组是有序的,有三种case:

(1)当前结果等于target,找到了pair;

(2)当前结果比target大,那么left右移只会使Sum更大,所以right左移

(3)当前结果比target小,那么right左移只会使Sum更小,所以left右移

所以每次只会有一个选择,从而实现线性就可以求出结果。该算法的时间复杂度是O(nlogn+n)=O(nlogn),空间复杂度取决于排序算法。

public int[] twoSum(int[] numbers, int target) {      int[] res = new int[2];      if(numbers==null || numbers.length<2)          return null;      Arrays.sort(numbers);      int left = 0;      int right = numbers.length-1;      while(left<right)   //不可能是 <=      {          if(numbers[left]+numbers[right]==target)  //case(1)        {              res[0] = number[left];              res[1] = number[right];              return res;          }          else if(numbers[left]+numbers[right]>target)//case(2)            right--;         else                                        //case(3)            left++;      }      return null;  } 

【后记1】返回的不是index,所以答案不对。方法是构造一个数据结构,包含数字的值和index,然后排序。

【后记2】以上解法没有找到所有解,面试会要求找出所有解。




0 0