C++, Python Solutions. O(n) time, O(n) space.


  • 0

    C++

    vector<int> twoSum(const vector<int>& nums, const int& target) {
        vector<int> res(2);
        unordered_map<int, int> map;
        for(int i = 0; i < nums.size(); ++i) {
            const auto it = map.find(target - nums[i]);
            if(it != map.end()) {
                res[0] = it->second;
                res[1] = i;
                return res;
            }
            map.insert({nums[i], i});
        }
        return res;
    }
    

    Python

    def twoSum(self, nums, target):
        d = {}
        for i in range(len(nums)):
            diff = target - nums[i]
            if diff in d:
                return [d[diff], i]
            d[nums[i]] = i
        return [-1, -1]
    

Log in to reply
 

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