美文网首页
[JavaScript LeetCode]1. Two Sum

[JavaScript LeetCode]1. Two Sum

作者: Instincts | 来源:发表于2017-06-05 21:21 被阅读25次

原题链接
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the *same *element twice.

代码

附上JavaScript版本

var twoSum = function(nums, target) {
    var len = nums.length;
    var map = new Map();
    
    for(var i = 0; i < len; i++) {
        var complement = target - nums[i];
        
        if (map.has(complement)) {
            return [map.get(complement), i];
        }
        
        map.set(nums[i], i);
    }
    
    return null;
};

相关文章

网友评论

      本文标题:[JavaScript LeetCode]1. Two Sum

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