1. Two Sum

来源:互联网 发布:域名必须实名认证吗 编辑:程序博客网 时间:2024/06/10 20:14

1. Two Sum

My Submissions
Total Accepted: 210007 Total Submissions: 937405 Difficulty: Easy

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.

74ms:

public class Solution {    public int[] twoSum(int[] nums, int target) {        int [] result=new int[2];        if(nums.length==2){            result[0]=0;            result[1]=1;        }        if(nums.length>2){            for(int i=0;i<nums.length-1;i++){                for(int j=i+1;j<nums.length;j++){                    if(nums[i]+nums[j]==target){                        result[0]=i;                        result[1]=j;                    }                }            }        }        return result;    }}

5ms:

public class Solution {    public int[] twoSum(int[] nums, int target) {        int[] nums_sorted=new int[nums.length];        System.arraycopy(nums,0,nums_sorted,0,nums.length);        //Quicksort.        Arrays.sort(nums_sorted);        //Find the two numbers. O(n)        int start=0;        int end=nums_sorted.length;        while(start<end){            while(nums_sorted[start]+nums_sorted[--end]>target);            if(nums_sorted[end]+nums_sorted[start]==target)                break;            while(nums_sorted[++start]+nums_sorted[end]<target);            if(nums_sorted[end]+nums_sorted[start]==target)                break;        }        //find the indices of the two numbers        int[] ret=new int[2];        int index=0;        int a=nums_sorted[start];        int b=nums_sorted[end];        for(int i=0;i<nums.length;i++)            if(nums[i]==a || nums[i]==b)                ret[index++]=i;        return ret;    }}

8ms:利用hash表
public class Solution {public static void main(String[] args) {int[] a = { 2, 7, 11, 15 };System.out.println(twoSum(a, 9));}public static int[] twoSum(int[] nums, int target) {        int[] result = new int[2];        int n2;        Integer idx;        Map<Integer, Integer> map = new HashMap<Integer, Integer>(nums.length);                for (int i = 0; i < nums.length; i++) {map.put(nums[i], i);}        for (int i = 0; i < nums.length - 1; i++) {n2 = target - nums[i];idx = map.get(n2);if(idx != null && idx > i){result[0] = i;result[1] = idx;break;}}        return result;    }}


1 0