首页 > 其他 > 详细

Two Sum

时间:2015-12-09 13:42:41      阅读:297      评论:0      收藏:0      [点我收藏+]
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;
    }
}

 

Two Sum

原文:http://www.cnblogs.com/codingEskimo/p/5032291.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!