数组 - 两数之和

题目

https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/1/array/29/

个人解法

测试用例数(个) 执行用时(ms) 战胜
29 168 64.74%
var twoSum = function(nums, target) {
    var sortNums = nums.map(function(v, i) {
        return {
            value: v,
            index: i
        }
    }).sort(function(prev, next) {
        return prev.value > next.value
            ? 1 : -1;
    });

    var startIndex = 0;
    var endIndex = sortNums.length - 1;

    while (startIndex < endIndex) {
        var sum = sortNums[startIndex].value + sortNums[endIndex].value;

        if (sum === target) {
            break;
        } else if (sum < target) {
            startIndex++;
        } else {
            endIndex--;
        }
    }

    return [
        sortNums[startIndex],
        sortNums[endIndex]
    ].sort(function(prev, next) {
        return prev.index > next.index ? 1 : -1;
    }).map(function(v) {
        return v.index;
    });
}

最快解法

测试用例数(个) 执行用时(ms) 战胜
21 56 100%
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    const map = {};
    for (let i = 0; i < nums.length - 1; i++) {
        map[target-nums[i]] = i;
        if (nums[i+1] in map) return [map[nums[i+1]], i+1];
    }
}

分析

「最快解法」巧用对象记录差值。

*****
Written by Zheng Yu on 14 May 2019