哈希表存储已经遍历过的数,遍历当前数时直接查找遍历过的数是否满足条件即可。
class Solution { public: vector<int> FindNumbersWithSum(vector<int> array,int sum) { unordered_set<int> hash; for (auto &i: array) { if (hash.count(sum - i)) return {i, sum - i}; hash.insert(i); } return {}; } };