题目地址:
https://www.acwing.com/problem/content/71/
输入一个数组和一个数字 s s s,在数组中查找两个数,使得它们的和正好是 s s s。如果有多对数字的和等于 s s s,输出任意一对即可。你可以认为每组输入中都至少含有一组满足条件的输出。
用一个哈希表存之前出现过的数字,遍历到 x x x时,找 s − x s-x s−x是否存在即可。代码如下:
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
vector<int> findNumbersWithSum(vector<int>& nums, int target) {
vector<int> res;
unordered_set<int> s;
for (int x : nums) {
if (s.count(target - x)) {
res.push_back(target - x);
res.push_back(x);
break;
}
s.insert(x);
}
return res;
}
};
时空复杂度 O ( n ) O(n) O(n), n n n是数组长度。