3-line JavaScript O(n) solution using map


  • 0
    var twoSum = function(nums, target) {
        const diffs = new Map();
        const j = nums.findIndex((a, i) => diffs.has(target - a) || diffs.set(a, i) && 0);
        return [diffs.get(target - nums[j]), j];
    };
    

    Or cheating into one line:

    var twoSum = function(nums, target, j, diffs = new Map()) {
        return [j = nums.findIndex((a, i) => diffs.has(target - a) || diffs.set(a, i) && 0), diffs.get(target - nums[j])];
    };
    

  • 0
    W

    @loctn thank your solution.by the way, there are any solutions? Because I have not learned Map.


  • 0

    Hey, @wcu1117 . You can use a regular JavaScript object:

    var twoSum = function(nums, target) {
        const diffs = {};
        for (let i = 0; i < nums.length; i++) {
            if (target - nums[i] in diffs) {
                return [diffs[target - nums[i]], i];
            } else {
                diffs[nums[i]] = i;
            }
        }
    };
    

  • 0
    H

    @loctn
    very Simple and elegant


Log in to reply
 

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