Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
O(n)
,空间复杂度为 O(n)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m;
for (int i = 0; i < size(nums); ++i) {
int t = target - nums[i];
if (m.count(t)) {
return {i, m[t]};
}
m.emplace(nums[i], i);
}
return {-1, -1};
}
};