[Leetcode] Two Sum (Java)

来源:互联网 发布:js的eval方法 编辑:程序博客网 时间:2024/05/29 21:34

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

求数组中两个数的和为给定的target值

首先想到的思路就是排序,然后两个指针,一个从前向后扫,一个从后向前扫,直到相遇,是个O(nlogn)的办法:

import java.util.Arrays;public class TwoSum {    public int[] twoSum(int[] numbers, int target) {        int start = 0,end = numbers.length-1;        int[] tempArray = Arrays.copyOf(numbers, numbers.length);        Arrays.sort(tempArray);        int temp = tempArray[start]+tempArray[end];        while(temp!=target) {        if(temp > target) {        end--;        }        else {start++;}        temp = tempArray[start]+tempArray[end];        }        int index1=-1,index2=-1;        for(int i = 0;i<numbers.length;i++) {        if(numbers[i]==tempArray[start] || numbers[i]==tempArray[end]) {        if(index1 == -1) {        index1 = i;        }        else if(index2 == -1){index2 = i;break;}        }        }        if(index2<index1){        int tem = index2;        index2 = index1;        index1 = tem;        }    return new int[]{index1+1,index2+1};    }    public static void main(String[] args) {    int[] numbers = {2,7,11,15};    int target = 9;int[] result = new TwoSum().twoSum(numbers, target);System.out.println("index1="+result[0]+",index2="+result[1]);}}
觉得太麻烦,又费力又费时,于是改成了Hash,为0(n):

import java.util.HashMap;import java.util.Map;public class TwoSum{    public int[] twoSum(int[] numbers, int target) {    Map<Integer, Integer> map = new HashMap<Integer, Integer>();    for(int i=0;i<numbers.length;i++) {    if(!map.containsKey(target-numbers[i])) {    map.put(numbers[i], i+1);    }else {    return new int[]{Math.min(i+1, map.get(target-numbers[i])),Math.max(i+1, map.get(target-numbers[i]))};    }    }    return null;    }    public static void main(String[] args) {    int[] numbers = {2,7,11,15};    int target = 9;int[] result = new TwoSum().twoSum(numbers, target);System.out.println("index1="+result[0]+",index2="+result[1]);}}



0 0
原创粉丝点击