LeetCode 1. 两数之和(易)

first_problem.png

考察知识点

数组、哈希表与循环控制

核心思想

双层循环或者hash map映射利用Key和Value的对应关系

基础解法

双层循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for(int i=0; i<nums.size(); i++){
for(int j=i+1; j<nums.size(); j++){ // 从i+1开始循环
if((nums[i] + nums[j]) == target){
result.push_back(i);
result.push_back(j);
return result;
}
}
}
return result;
}
};

进阶解法

核心思想:遍历数组,每次都记录:哈希表[target - 当前数字] = 当前数字的索引,那么在往后的遍历中如果遇到map的键值包含当前数字的情况,说明之前的某个数字可以和当前数字加和为target,返回俩个数字的索引即可。

  • 5行版本
1
2
3
4
5
6
7
8
9
10
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> m;
for(int i = 0; i < nums.size(); m[target - nums[i - 1]] = i++){
if(m.count(nums[i])) return {m[nums[i]], i};
}
return {-1, -1};
}
};

对上述代码的解释:

写法上需要清楚C++中for循环的执行顺序: 1.初始化i为0 2.判断i是否小于数组长度,满足条件执行③,否则跳出循环 3.执行for语句对应的{}中的代码 4.执行m[target - nums[i - 1]] = i++ a.执行右边的表达式i++,记录结果为当前的i所拥有的值,并使得此时变量i的值递增一步 b.计算target - nums[i - 1],此时i的值为用于赋值的值 + 1,所以i - 1 = 用于赋值的值 c.写入哈希表 此行代码等同于m[target - nums[i]] = i; i++;

这样的代码,可读性太差。为了压缩代码量而压缩,不是很合适。

另一个C++版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 1. Two Sum
// https://leetcode.com/problems/two-sum/description/
// 时间复杂度:O(n)
// 空间复杂度:O(n)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> record; // 声明
for(int i = 0 ; i < nums.size() ; i ++){
int complement = target - nums[i];
if(record.find(complement) != record.end()){
int res[] = {i, record[complement]};
return vector<int>(res, res + 2);
}
record[nums[i]] = i; // 永远以下标i为record的value 以值nums[i]为record的key 以便于后续查找
}
}
};

unordered_map(c++ reference)是c++ 哈希表的实现模板,在头文件中,存储key-value的组合,unordered_map可以在常数时间内,根据key来取到value值。

如果key存在,则find返回key对应的迭代器,如果key不存在,则find返回unordered_map::end。因此可以通过

1
map.find(key) != map.end()  // 为True时key存在 为False时Key不存在

来判断,key是否存在于当前的unordered_map中。

思想类似,可读性好一些。

Python版本

1
2
3
4
5
6
7
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d = {}
for i,num in enumerate(nums):
if target-num in d: # 这里d == d.keys()
return [d[target-num], i]
d[num] = i # 以下标为value 以值为key

同样的思想,python写法较为为简单。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!