题目
给定一个数组,以及一个target值,找出这个数组中的两个数,使得两数之和刚好等于 target 值。并返回这两个数的下标。
原题链接: https://leetcode-cn.com/problems/two-sum/
思路
维护一个哈希表,key 为数字,value 为 index。 这样能够快速的获得数字的下标。
然后遍历数组,假设当前数字为 x,在哈希表中查找是否有 target - x,如果有,则 x 和 target - x 即是想要的两个数,返回相应的 index 即可;反之,将 x 加入到哈希表中。
- 复杂度分析
- 时间复杂度 O(n),遍历一次数组即可,且O(1)地查找 target - x。
- 空间复杂度 O(n),主要是哈希表的开销。
代码
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> table;
for (int i = 0; i < nums.size(); i++) {
int cur = nums[0];
int rest = target - cur;
if (table.find(rest) != table.end()) {
return {table[rest], i};
}
else {
table[cur] = i;
}
}
return {};
}
};