美文网首页
1 - 1. Two Sum

1 - 1. Two Sum

作者: bestCindy | 来源:发表于2022-06-18 23:30 被阅读0次

https://leetcode.com/problems/two-sum/

var twoSum = function(nums, target) {
    let result = [0, 0];
    for (let i = 0; i < nums.length; i++) {
        const rest = target - nums[i];
        let restIndex = nums.indexOf(rest);
        if (restIndex != -1 && restIndex != i) {
            result = [i, restIndex];
            break;
        }
    }
    return result;
};

the case restIndex === i was not considered the first time I submitted so I add restIndex != i in if condition

we can also set the second parameter of indexOf to avoid that case

so the restIndex calucation can be changed to let restIndex = nums.indexOf(rest, i + 1);

some other good methods

using ES6 data structure Map

var twoSum = function(nums, target) {
    let map = new Map();
    for (let i = 0; i < nums.length; i++) {
        let rest = target - nums[i];
        if (map.get(rest) != undefined) {
            result = [i, map.get(rest)];
            return result;
        } else {
            map.set(nums[i], i);
        }
    }
    return [0, 0]
};

this is more efficient

we need to notice the case map.get(rest) === 0

and we can instead map to an ordinary object

var twoSum = function(nums, target) {
    let obj = {};
    for (let i = 0; i < nums.length; i++) {
        let rest = target - nums[i];
        if (obj[rest] != undefined) {
            result = [obj[rest], i];
            return result;
        } else {
            obj[nums[i]] = i;
        }
    }
    return [0, 0]
};

相关文章

  • LeetCode 1. Two Sum (Easy)

    LeetCode 1. Two Sum (Easy) LeetCode 1. Two Sum (Easy) 原题链...

  • 1. Two Sum

  • 1. Two Sum

    Given an array of integers, return indices of the two num...

  • 1. Two Sum

    Description Given an array of integers, return indices of...

  • 1. Two Sum

    Problem Given an array of integers, return indices of the...

  • 1. Two Sum

    Given an array of integers, return indices of the two num...

  • 1. Two Sum

    Leetcode: 1. Two SumGiven an array of integers, return in...

  • 1. Two Sum

    Example:Given nums = [2, 7, 11, 15], target = 9,Because n...

  • 1. Two Sum

    描述 Given an array of integers, return indices of the two ...

  • 1. Two Sum

    Description Given an array of integers, return indices of...

网友评论

      本文标题:1 - 1. Two Sum

      本文链接:https://www.haomeiwen.com/subject/rfllvrtx.html