Friday, February 15, 2013

[LeetCode] Two Sum


Thought:
    The O(n^2) algorithms is trivial. But it seems we could improve it to O(nlgn) at the cost of some extra space.
    The idea is to sort the array first in O(nlgn) and then find the answer by using 2 pointers in O(n) time.
    The first tricky thing is how we store the index of the unsorted array, try HashMap in O(n) time and O(n) space!
    The second tricky thing is about the duplicates in the array. When we are hashing, we might find that there are duplicates( the key is already in the HashMap). Actually we could directly check if they are exactly the answer, if yes, we return, and if not, we could just skip this new key. Why? It is because the problem tells us there is exactly one solution. It must be the case that either of them will appear in the final answer.

Code in JAVA:
public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] result = new int[2];
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < numbers.length; i++){
            if( !map.containsKey(numbers[i]) ){
                map.put(numbers[i], i+1);
            }else if( 2 * numbers[i] == target){
                result[0] = map.get(numbers[i]);
                result[1] = i + 1;
                return result;
            }            
        }     
        Arrays.sort(numbers);
        int i = 0;
        int j = numbers.length - 1;
        while( i < j ){
            if( numbers[i] + numbers[j] > target ){
                j--;
            }else if( numbers[i] + numbers[j] < target ){
                i++;
            }else{  
                result[0] = Math.min(map.get(numbers[i]), map.get(numbers[j]));
                result[1] = Math.max(map.get(numbers[i]), map.get(numbers[j]));             
                return result;
            }
        }   
        return result;
    }
}

1 comment:

  1. why do you need to sort it when you already build the hashmap, which means you could just get the (target - number[i]) value from the map in constant time? so the time complexity would be O(n) and with O(n) space.

    ReplyDelete