1 两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

暴力解法,使用两层循环计算所有的和,符合条件则返回。时间复杂度 \(O(n^2)\),空间复杂度 \(O(1)\)

    public int[] twoSum(int[] nums, int target) {
        int length = nums.length;
        for (int i = 0; i < length-1; i++) {
            for (int j = i+1; j < length; j++) {
                if (nums[i]+nums[j]==target){
                    return new int[]{i,j};
                }
            }
        }
        return null;
    }

因为符合条件的两数之和是一一对应的关系,因此可以将数作为key,与目标值之间的差作为value存入散列表中(key和value可以互换)

则只用遍历一次数组,时间复杂度为 \(O(n)\),空间复杂度为 \(O(n)\)

	public int[] twoSum(int[] nums, int target) {
        int len = nums.length;
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(len-1);
        for(int i = 0; i<len; ++i){
            int another = target - nums[i];
            if(map.containsKey(another)){
                return new int[]{map.get(another),i};
            }
            map.put(nums[i], i);
        }
        return null;
    }
posted @ 2020-11-20 09:34  PotatoTed  阅读(89)  评论(0)    收藏  举报