今天开始,打算每天写一道Leetcode上面的题目
开始呗...
另外,嗯..不知道有没有同学们有没有一块来刷leetcode的,组个队啊!
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解决方案一:
var twoSum = function(nums, target) {
var map = new Map();
var len = nums.length;
for (let i = 0; i< len; i++) {
map.set(nums[i], i);
}
var comp;
for (let i = 0; i < len; i++) {
comp = target - nums[i];
if (map.has(comp) && map.get(comp) != i)
return [i, map.get(comp)];
}
console.log("No two sum solution");
};
}
解决方案二:
第二种解决方案比第一种大约快了一倍的样子,很强.
var twoSum = function(nums, target) {
var map = {};
var len = nums.length;
for (var i = 0; i < len; i++) {
var complement = target - nums[i];
var n = map[complement];
if(n >= 0) {
return [n, i];
}
map[nums[i]] = i;
}
return undefined;
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。