[LeetCode] 1. Two Sum

public class Solution {
    public int[] twoSum(int[] nums, int target) {
         /* Basic idea: Load the array into a hashMap with the value of each array element as key and index of the array as value
           Interate through the key, and check whether "target - value" is in the map. 
           Save the array index and sort it
           
           Special case: The array contains duplicate elements.  
           1) The target value is not or only related to the one of the duplicate value => store the first one.
           2) The target value is twice of the duplicate value => directly store the two indexes and return output.
        */
        
        int[] results = new int[2];
        Map<Integer, Integer> numsMap = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++){
            if (numsMap.containsKey(nums[i])){
                /*It has duplicated number
                 if 1) duplication is the results, return
                    2) drop the second, if it is put back to the map, value(index) got overide */
                if (2 * nums[i] == target){
                    results[0] = numsMap.get(nums[i]); // it stores as index when the Hash is created
                    results[1] = i + 1;  // i start at 0, so need to +1 as index
                    return results;
                } 
            } else {
                numsMap.put(nums[i], i+1); //the array index start at 0;
            }
        }
        
        for(Integer key : numsMap.keySet()){
            if (numsMap.containsKey(target - key)){
                int a = numsMap.get(key);
                int b = numsMap.get(target-key);
                if (a < b){
                    results[0] = a;
                    results[1] = b;
                } else {
                    results[0] = b;
                    results[1] = a;
                }
            }
        }
        return results;
    }
}

 

posted on 2015-12-09 11:34  codingEskimo  阅读(103)  评论(0编辑  收藏  举报

导航