One Pass Hash C++ O(n) Solution

  • 0

    I tried to make my solution as concise as possible, but it's been a while since I touched C++.

    The runtime was 6 ms.

    class Solution {
        vector<int> twoSum(vector<int>& nums, int target) {
            unordered_map<int,int> val2index;
            // Map first index to value
            val2index[nums[0]] = 0;
            for (int i=1; i < nums.size(); ++i) {
                // Find Complements in map
                int complement = target - nums[i];
                unordered_map<int,int>::const_iterator found = val2index.find(complement);
                if (found != val2index.end()) {
                    return vector<int>({got->second,i});
                // Map all index of nums to values
                val2index[nums[i]] = i;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.