[JavaScript LeetCode]1. Two Sum

2017-06-05  本文已影响25人  Instincts

原题链接
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;
};
上一篇 下一篇

猜你喜欢

热点阅读