7 line C++ code, 0ms, beats 100%


  • 0
    V
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            unordered_map<int, int> m;
            for (int i = 0; i < nums.size(); ++i) {
                int j = m[target - nums[i]];
                if (j) return {j - 1, i};
                m[nums[i]] = i + 1;
            }
            return {-1, -1};
        }
    };
    

  • 0
    V

    Very simple idea. For each number, we record a map from its value to its index + 1. If for a number x, n - x maps to a non-zero number, it means that n - x exist somewhere before in the array.


Log in to reply
 

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