Two Sum

题目:

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.

分析:

使用排序的方法,有机会可以重新做一下

解法:

public class Solution {
    /*
     * @param numbers : An array of Integer
     * @param target : target = numbers[index1] + numbers[index2]
     * @return : [index1 + 1, index2 + 1] (index1 < index2)
     */
    public int[] twoSum(int[] numbers, int target) {
        // write your code here
        int res[] = new int[2];
        if (numbers.length == 0) {
            return res;
        }
        HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>();
        for (int i = 0; i < numbers.length; i++) {
            if (hash.containsKey(numbers[i]) ) {
                res[0] = hash.get(numbers[i]) + 1;
                res[1] = i + 1;
                break;
            }
            hash.put(target - numbers[i], i);
        }
        return res;
    }
}

results matching ""

    No results matching ""