JavaScript O(n) Solution


  • 0
    D

    This assumes that values passed to twoSum() are valid.

    const twoSum = function(nums, target) {    
        let map = new Map()
    
        for (let i = 0; i < nums.length; i++) {
            if (map.has(nums[i])) {
                return [map.get(nums[i]), i]
            }
            map.set( ( target - nums[i] ), i ) // required : index
        }
        throw new Error('No match.')
    }
    

Log in to reply
 

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