LeetCode: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 <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • 只会存在一个有效答案

题解1(暴力)执行用时 47ms 消耗内存 13.8MB

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

题解2 (使用hash表)执行用时 2ms 消耗内存 14.6MB

思想:使用hash表记录值和下表

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) {
std::unordered_map<int, int> hashTable;
for (int i = 0; i < nums.size(); i++) {
auto itor = hashTable.find(target - nums[i]);
if (itor != hashTable.end()) {
return {itor->second, i};
}
hashTable[nums[i]] = i;
}
return {};
}
};

总结:

  1. 可以看到暴力解法 和 使用hash表在时间复杂度上相差巨大
  2. 使用hash表利用空间换时间,每次查找的时间复杂度为O(1)