Two Sum

13 篇文章 0 订阅
7 篇文章 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


Analysis: 

See: http://yucoding.blogspot.com/2013/03/leetcode-question-113-two-sum.html


What happens when a duplicate key is put into a HashMap? 

You may find your answer in the javadoc of Map#put(K, V)  (which actually returns something):

public V put(K key,
             V value)

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for this key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k)  would return true.)

Parameters:
key - key with which the specified value is to be associated.
value - value to be associated with the specified key.

Returns:
previous value associated with specified key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with the specified key, if the implementation supports null values.)

So if you don't assign the returned value when calling mymap.put("1", "a string"), it just becomes unreferenced and thus eligible for garbage collection.

http://stackoverflow.com/questions/1669885/what-happens-when-a-duplicate-key-is-put-into-a-hashmap


Code: 

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        int first=0, second=0;
        int[] res = new int[2];
        
        for(int i=0; i<=numbers.length-1; i++) {
            map.put(numbers[i], i);
        }
        
        for(int j=0; j<=numbers.length-1; j++) {
            if(map.containsKey(target-numbers[j]) && map.get(target-numbers[j])!=j) {   // still correct if duplicates exist !!!
                if(map.get(target-numbers[j]) > j) {
                    res[0] = j + 1;
                    res[1] = map.get(target-numbers[j]) + 1;
                }
                else {
                    res[0] = map.get(target-numbers[j]) + 1;
                    res[1] = j + 1;
                }
                break;
            }
        }
        
        return res;
    }
}


Update: 30/01/2014

Use two pointers. However, as for this problem, since the indexes need to be returned, the first approach is much better. 

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] original = Arrays.copyOf(numbers, numbers.length);
        Arrays.sort(numbers);
        int low=0, high=numbers.length-1;
        int[] res = new int[2];
        while(low < high) {
            if(numbers[low]+numbers[high]<target) low++;
            else if(numbers[low]+numbers[high]>target) high--;
            else if(numbers[low]+numbers[high]==target) {
                boolean first = false;
                for(int i=0; i<original.length; i++) {
                    if(!first && original[i]==numbers[low]) {
                        res[0] = i+1;
                        first = true;
                    }
                    if(original[i]==numbers[high]) res[1]=i+1;
                }
                Arrays.sort(res);
                break;
            }
        }
        return res;
    }
}


Update 02/08/2014: 

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        int[] res = new int[2];
        
        for(int i=0; i<=numbers.length-1; i++) {
            if(map.containsKey(target-numbers[i])) {    // find the pair
                res[0] = map.get(target-numbers[i]);
                res[1] = i+1;   // the current index must be the larger one
                break;
            }
            else map.put(numbers[i], i+1);  // does not match, just store the number and index
        }
        return res;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值