-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_sum.cc
More file actions
19 lines (17 loc) · 696 Bytes
/
two_sum.cc
File metadata and controls
19 lines (17 loc) · 696 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "two_sum.h"
#include <unordered_map>
#include <vector>
std::vector<int> twoSum(const std::vector<int> &nums, const int target) {
const int numCount = static_cast<int>(nums.size());
std::unordered_map<int, int> indexOf;
indexOf.reserve(nums.size()); // Reserve space to avoid rehashing
for (int idx = 0; idx < numCount; ++idx) {
const int num = nums[idx];
const int need = target - num;
if (auto iterator = indexOf.find(need); iterator != indexOf.end()) {
return {iterator->second, idx};
}
indexOf.emplace(num, idx); // Note: no overwrite if x already exists
}
return {-1, -1}; // If no solution is found
}