2016年6月24日星期五

[LeetCode] #1 Two Sum

Thinking:
1) Brute force: O(n^2)
2) Sort + extra array to store index info O(nlogn) + O(n) space
3) Hash, <k,v> = <Value, Index> O(n) + O(n) space

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[] result = new int[2];
        if (numbers == null || numbers.length == 0) {
            return result;
        }
        
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        
        for (int i = 0; i < numbers.length; i++) {
            map.put(numbers[i], i);
        }
        
        for (int i = 0; i < numbers.length; i++) {
            if (map.containsKey(target - numbers[i])) {
                result[0] = i + 1;
                result[1] = map.get(target - numbers[i]) + 1;
                return result;
            }
        }
        
        return result;
    }
}


没有评论:

发表评论