📔
Casey's Problem Set
  • Welcome
  • LeetCode
    • 1 - 100
      • 1. 两数之和
      • 10. 正则表达式匹配
Powered by GitBook
On this page
  • 题目描述
  • 题解
  • 知识点
  1. LeetCode
  2. 1 - 100

1. 两数之和

Previous1 - 100Next10. 正则表达式匹配

Last updated 3 months ago

题目描述

给定一个整数数组 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(n2) 的算法吗?

题解

题解

首先考虑暴力解法(brutal solution),遍历数组,得到所有的下标组合 (i,j),然后判断 nums[i] + nums[j] 是否等于 target。这种做法的时间复杂度为 O(n^2) 显然不够好。

对于已经遍历过的序列,我们可以将其置入一个哈希表中,在每次遍历到新的元素时,从哈希表中查找前面是否有满足条件的元素同当前的元素相加为 target。哈希表查找的时间复杂度为 O(1),因此算法的整体时间复杂度降低到 O(n)。

C++
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res(2, 0);
        unordered_map<int, int> um;
        for (int i = 0; i < nums.size(); i++) {
            if (um.find(target - nums[i]) == um.end()) {
                um[nums[i]] = i;
            }
            else {
                res[1] = i;
                res[0] = um[target - nums[i]];
            }
        }
        return res;
    }
};
Go
func twoSum(nums []int, target int) []int {
    m := make(map[int]int, len(nums))
    for i, n := range nums {
        j, ok := m[target - n]
        if ok {
            return []int{j, i}
        } else {
            m[n] = i
        }
    }
    return []int{}
}

知识点

  1. 在 C++ 中哈希表可以调用 unordered_map<int, int>,Go 中则使用 map[int]int。

力扣
原题链接
Logo