summaryrefslogtreecommitdiff
path: root/top-interview-questions/easy/array/09_two_sum.cc
blob: 72d2014f12b9a8de2e4af1cf735367564dba38e9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // When you find, e.g., 2, map (2 -> idx 0) for the event
        // in which you find the 7.
        std::vector<int> pair(2);
        std::unordered_map<int, int> 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;
    }
};