Skip to content

Latest commit

 

History

History
68 lines (60 loc) · 2.12 KB

1. Two Sum.md

File metadata and controls

68 lines (60 loc) · 2.12 KB

#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.

思路:因为做过Contains Duplicate这套题目...直接想到用hashmap来存储数据,一个trick就是不需要全部存进去,而是边存边检查是否有合适的结果。而实际上...只需要复制一次数组,把duplicateArrays.sort一下,然后使用两个指针就好了,找到对应的值之后再去遍历原数组获取index的值就好了。

Java Solution(HashMap)

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> hashmap = new HashMap<Integer,Integer>();
        for(int i=0;i<nums.length;i++){
            if(hashmap.containsKey(target - nums[i])){
                int[] tar = new int[2];
                tar[0] = hashmap.get(target-nums[i]);
                tar[1] = i;
                return tar;
            }
            hashmap.put(nums[i],i);
        }
        return null;
    }
}

**Java Solution(Sort&TwoPointer)**faster than the solution by hashmap

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] copy = Arrays.copyOf(nums,nums.length);
        Arrays.sort(copy);
        int[] result = {0,0};
        int i=0,j=0;
        while(j<nums.length-1){
            j++;
            if(copy[0]+copy[j]>target) break;
        }
        while(true){
            if(i<nums.length&&copy[i]+copy[j]<target){
                i++;
            }else if(j>0&&copy[i]+copy[j]>target){
                j--;
            }else break;
        }
        for(int m=0,n=0;m<nums.length;m++){
            if(nums[m]==copy[i]||nums[m]==copy[j]){
                result[n] = m;
                n++;
                if(n==2) break;
            }
        }
        return result;
    }
}