1.两数之和

550 阅读1分钟

1.题目

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 你可以按任意顺序返回答案。

示例1:

输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

输入:nums = [3,2,4], target = 6 输出:[1,2]

示例 3:

输入:nums = [3,3], target = 6 输出:[0,1]

提示:

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • 只会存在一个有效答案

进阶:你可以想出一个时间复杂度小于 O(n²) 的算法吗?

2.答题

2.1 暴力解法

使用类似冒泡的方式,利用双循环两两计算和,得出结果

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

时间复杂度

由于使用了循环的嵌套,判读语句代码块执行了n²次,所以为:O(n²)

空间复杂度

在函数开始执行时初始化了result数组,其他无新增空间占用,为常量空间复杂度:O(1)

提交结果

暴力解法-提交结果

尝试优化

怎么将时间复杂度降到小于 O(n²)?

思路1:

对数组排序,使用前后双指针,排序使用时间复杂度为O(nlogn)的排序,使用一个循环可以比较出结果,但是这样会打乱数组,数组下标会乱,需要用一个数据结构存储下标

整个过程就是:

  • 声明HashMap用于存储原数组的值和下标
  • 循环数组,将数据存入HashMap
  • 对数组进行排序
  • 循环数组,使用双指针,两数和小于target,前指针后移,两数和大于target,后指针前移,相等,则从HashMap取出相应值的下标

时间复杂度为:O(n + nlogn + n) = O(nlogn)

空间复杂度:因为使用了HashMap,O(n)

时间复杂度小了,好像逻辑更复杂了。。。

思路2:

双循环中,第二层循环的目的是,从数组中查找值为target-self的值,采用循环的方式肯定是O(n),上面👆用到了HashMap,已知HashMap的查询时间复杂度为O(1),如果使用HashMap来做查询的话,时间复杂度肯定会减小

整个过程就是:

  • 声明HashMap用于存储数组的值和下标
  • 循环数组,在HashMap中查找值为target-self的值,若不存在,则将当前值存在,若存在,则从HashMap取出相应值的下标

时间复杂度为:O(n) = O(n)

空间复杂度:因为使用了HashMap,O(n)

时间复杂度小了,逻辑比上面简单多了,我们分别尝试一下

2.2 排序+双指针

class Solution {
    class Test {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        //缓存,使用List可以存储值相同的元素,也可以偷懒忽略
        Map<Integer, List<Integer>> cache = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (cache.containsKey(nums[i])) {
                cache.get(nums[i]).add(i);
                continue;
            }
​
            List<Integer> array = new ArrayList<>();
            array.add(i);
            cache.put(nums[i], array);
        }
​
        //偷懒,使用系统提供的排序方法
        Arrays.sort(nums);
​
        //前后双指针移动
        int head = 0;
        int tail = nums.length - 1;
        while (head < tail) {
            if (nums[head] + nums[tail] == target) {
                int i = cache.get(nums[head]).remove(0);//防止相同元素
                int j = cache.get(nums[tail]).get(0);
                result[0] = i;
                result[1] = j;
                return result;
            } else if (nums[head] + nums[tail] > target) {
                tail--;
            } else {
                head++;
            }
        }
        return result;
    }
}

提交结果

排序+双指针-提交结果

执行时间从56ms提升到了8ms,内存消耗从38.5MB弱化到了39MB,尝试一下一个解法

2.3 HashMap

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        //缓存
        Map<Integer, Integer> cache = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int key = target - nums[i];
            if (cache.containsKey(key)) {
                result[0] = cache.get(key);
                result[1] = i;
                return result;
            }
            cache.put(nums[i], i);
        }
        return result;
    }
}

提交结果

HashMap-提交结果

如果不对的地方请指出,有其他解决方法的,也可以留言,作为新手,也在学习当中,谢谢浏览。