1. Two Sum
- 暴力算法
- 哈希表
题目
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路
- 暴力算法:遍历元素,找到两个相加得target值的数字。
- 复杂性分析:
- 时间复杂度:O(n^2).
- 空间复杂度:O(1).
题解
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
for (int i = 0; i < nums.size(); i++) {
for (int j = i+1; j < nums.size(); j++) {
if (nums[i] + nums[j] == target) {
ans.push_back(i);
ans.push_back(j);
return ans;
}
}
}
ans.push_back(-1);
ans.push_back(-1);
return ans;
}
};
优化
思路
上述方法是在不动数组的基础上,用两层遍历来确定基础数字和匹配数字,因此时间复杂度为O(n)*O(n). 事实上,只需要确定了一个基础数字,匹配数字的查找可以用哈希表查询来节省时间。
哈希表的查找元素的时间复杂度是O(1),可以将时间复杂度降为O(n)*O(1)=O(n). 但哈希表需要存储n个元素的额外空间,因此空间复杂度升为O(n)。
代码
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
map<int, int> hashMap;
for (int i = 0; i < nums.size(); i++) {
if (hashMap.find(target-nums[i]) != hashMap.end()) {
ans.push_back(hashMap[target-nums[i]]);
ans.push_back(i);
return ans;
}
// 查询完毕后添加,避免自身查询
hashMap[nums[i]] = i;
}
// 无解
ans.push_back(-1);
ans.push_back(-1);
return ans;
}
};
反思
- 关于哈希表查找,原本是先添加完再逐一查找,忽略了避免自身相匹配的问题,导致出错
解决方法:1)找到匹配数字后检验是否与基础数字一致;2)直接在查找完毕之后再添加。 - 该题的优化点在于数字的匹配查找。
解题思路:暴力查找(O(n^2))->排序查找(O(nlogn))->哈希查找(O(n))。