Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

自己的思路:数组先排序,然后从两头开始找,借助HashMap存储数组的值到索引的映射。

时间复杂度:o(n * log(n)) 排序部分

public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        int len = nums.length;
        //利用HashMap记录数组的值到索引的映射
        //重复的key,HashMap会覆盖,对于两个相同的数即为所求,则输出的索引会出错 [3,3] 6 如果不做处理,则输出[1,1]
        //存入HashMap的过程中进行key判断
        HashMap<Integer, Integer> value2index = new HashMap<Integer, Integer>(len);
        for(int i = 0; i < len; i++){
            int num = nums[i];
            if(value2index.containsKey(num)){
                if(num + num == target){
                    result[0] = value2index.get(num);
                    result[1] = i;
                    return result;
                }
            }else{
                value2index.put(num, i);
            }
        }
        Arrays.sort(nums);
        int low = 0, high = len - 1;
        while(low < high){
            int sum = nums[low] + nums[high];
            if(sum == target){
                result[0] = value2index.get(nums[low]);
                result[1] = value2index.get(nums[high]);
                return result;
            }else{
                if(sum < target){
                    low ++;
                }else{
                    high --;
                }
            }
        }  
        return null;
    }

 

别人的思路:遍历数组,当遍历到一个数的时候,查找另外所需的数是否在数组中(利用hashmap存储值到索引的映射)

时间复杂度:o(n)

public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        int len = nums.length;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(len);
        for(int i = 0; i<len; i++){
            int numToFind = target - nums[i];
            if(map.containsKey(numToFind)){
                result[0] = map.get(numToFind);
                result[1] = i;
                return result;
            }
            map.put(nums[i], i);
        }
        return null;
        
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章