Leetcode 1. 两数之和(Two sum)

发布时间 2023-08-24 12:48:02作者: Ahci

题目链接?

给定一个整数数组 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]

提示:

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

思路

有人相爱,有人夜里开车看海,有人leetcode第一题都做不出来。 ——Leetcode评论

好经典的第一题,最简单的思路是使用两个for循环的暴力解法,注意判断条件不要写成i + j == target即可。时间复杂度为O(N^2)。

若要想使时间复杂度达到O(N)则需要使用查找插入删除的时间复杂度为O(1)的哈希表。只使用一个for循环,每次先检查哈希表中是否存在target - nums[i]的值, 若存在则直接返回,若不存在则存入nums[i]

代码实现

暴力解法:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];  // 定义返回数组
        for(int i = 0; i < nums.length; i++) {  // 第一个值
            for(int j = i + 1; j < nums.length; j++) {  // 第二个值
                if(nums[i] + nums[j] == target) {
                    res[0] = i;
                    res[1] = j;
                    break;
                }
            }
        }

        return res;
    }
}

HashSet:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        if(nums.length == 0 || nums == null) {
            return res;
        }

        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++) {
            int temp = target - nums[i];
            if(map.containsKey(temp)) {
                res[0] = i;
                res[1] = map.get(temp);
                break;
            }
            map.put(nums[i], i);
        }

        return res;
    }
}