题目描述

  • 序号:1
  • 题目:两数之和
  • 难度:简单
  • 标签:数组、哈希表
题目描述

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例 1:

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

示例 2:

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

示例 3:

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

提示:

  • $2 <= nums.length <= 10^4$
  • $-10^9 <= nums[i] <= 10^9$
  • $-10^9 <= target <= 10^9$
  • 只会存在一个有效答案

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


题解-方法1(枚举法)

思路

  • 暴力枚举
  • 遍历数组中所有的数字,查找符合求和满足条件的值。内层循环查找的开始位置可以是外层循环位置的后一位,因为前方的值已经匹配过,无需遍历。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
for(int i = 0; i < len; i++){
for(int j = i+1; j < len; j++){
if(nums[i]+nums[j] == target){
return new int[]{i, j};
}
}
}
return null;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int len = nums.size();
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (nums[i] + nums[j] == target) {
return {i, j};
}
}
}
return {};
}
};

复杂度分析

  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(1)$

题解-方法2(哈希表)

思路

  • 哈希表
  • 通过哈希表可以将内层时间复杂度O(n)降为O(1)。在哈希表中询问是否存在target - nums[i]的值,不存在则将当前值存入哈希表。

代码

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashTable = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (hashTable.containsKey(target - nums[i])) {
return new int[]{hashTable.get(target - nums[i]), i};
}
hashTable.put(nums[i], i);
}
return null;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashTable;
for (int i = 0; i < nums.size(); i++) {
if (hashTable.find(target - nums[i]) != hashTable.end()) {
return {hashTable[target - nums[i]], i};
}
hashTable[nums[i]] = i;
}
return {};
}
};

复杂度分析

  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$