From 4689e4e80b479be25f7557d05818f5caa723aafa Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Wed, 5 Feb 2025 18:36:31 -0800 Subject: Initial commit. --- top-interview-questions/easy/array/09_two_sum.cc | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 top-interview-questions/easy/array/09_two_sum.cc (limited to 'top-interview-questions/easy/array/09_two_sum.cc') 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 @@ +class Solution { +public: + vector twoSum(vector& nums, int target) { + // When you find, e.g., 2, map (2 -> idx 0) for the event + // in which you find the 7. + std::vector pair(2); + std::unordered_map val_to_idx; + + for (size_t i = 0; i < nums.size(); ++i) { + const int other = target - nums[i]; + const auto other_idx = val_to_idx.find(other); + + if (other_idx != val_to_idx.end()) { + pair[0] = i; + pair[1] = other_idx->second; + break; + } + + val_to_idx[nums[i]] = i; + } + + return pair; + } +}; -- cgit v1.2.3