2015年6月7日星期日

[LeetCode] Two Sum

Problem:

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

Java Code:

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        if (numbers == null || numbers.length < 2) {
            return result;
        }
        
        HashMap<Integer, ArrayList<Integer>> hs = new HashMap<Integer, ArrayList<Integer>>();
        
        for (int i = 0; i < numbers.length; i++) {
            if (hs.containsKey(numbers[i])) {
                hs.get(numbers[i]).add(i);
            } else {
                ArrayList<Integer> value = new ArrayList<Integer>();
                value.add(i);
                hs.put(numbers[i], value);
            }
        }
        
        for (int i = 0; i < numbers.length; i++) {
            int temp = target - numbers[i];
            if (hs.containsKey(temp)) {
                if (temp == numbers[i] && hs.get(temp).size() >= 2) {
                    result[0] = Math.min(hs.get(temp).get(0), hs.get(temp).get(1)) + 1;
                    result[1] = Math.max(hs.get(temp).get(0), hs.get(temp).get(1)) + 1;
                    break;
                } else if (temp != numbers[i]) {
                    result[0] = Math.min(i, hs.get(temp).get(0)) + 1;
                    result[1] = Math.max(i, hs.get(temp).get(0)) + 1;
                    break;
                }
            }
        }
        
        return result;
    }
}

没有评论:

发表评论