diff options
| author | 3gg <3gg@shellblade.net> | 2025-02-05 18:36:31 -0800 |
|---|---|---|
| committer | 3gg <3gg@shellblade.net> | 2025-02-05 18:36:31 -0800 |
| commit | 4689e4e80b479be25f7557d05818f5caa723aafa (patch) | |
| tree | 4df25811fe2a9a15b401375178da6537f4b6063f /top-interview-questions/easy/array/09_two_sum.cc | |
Diffstat (limited to 'top-interview-questions/easy/array/09_two_sum.cc')
| -rw-r--r-- | top-interview-questions/easy/array/09_two_sum.cc | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/top-interview-questions/easy/array/09_two_sum.cc b/top-interview-questions/easy/array/09_two_sum.cc new file mode 100644 index 0000000..72d2014 --- /dev/null +++ b/top-interview-questions/easy/array/09_two_sum.cc | |||
| @@ -0,0 +1,24 @@ | |||
| 1 | class Solution { | ||
| 2 | public: | ||
| 3 | vector<int> twoSum(vector<int>& nums, int target) { | ||
| 4 | // When you find, e.g., 2, map (2 -> idx 0) for the event | ||
| 5 | // in which you find the 7. | ||
| 6 | std::vector<int> pair(2); | ||
| 7 | std::unordered_map<int, int> val_to_idx; | ||
| 8 | |||
| 9 | for (size_t i = 0; i < nums.size(); ++i) { | ||
| 10 | const int other = target - nums[i]; | ||
| 11 | const auto other_idx = val_to_idx.find(other); | ||
| 12 | |||
| 13 | if (other_idx != val_to_idx.end()) { | ||
| 14 | pair[0] = i; | ||
| 15 | pair[1] = other_idx->second; | ||
| 16 | break; | ||
| 17 | } | ||
| 18 | |||
| 19 | val_to_idx[nums[i]] = i; | ||
| 20 | } | ||
| 21 | |||
| 22 | return pair; | ||
| 23 | } | ||
| 24 | }; | ||
