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) {
let num=new Array();
for(let i=0;i<nums.length;i++){
for(let j=nums.length-1;j>i;j--){
if(nums[i]+nums[j]==target){
num.push(i);
num.push(j);
}
}
}
return num;
};
我按照最基本的数组方法写了一个,但是时间复杂度高O(n^2),看了别人的改进算法运用Map,时间复杂度为O(n)。
var twoSum = function(nums, target) {
let map = new Map();//Map是键值对集合
let c=[];//创建数组
for(let i = 0; i < nums.length; i ++) {
if(map.has(target - nums[i])) {//map.has()查看map中是否有这个值,返回值为true或false
c.push([map.get(target - nums[i]), i]);//如果有,使用map.get()返回这个键对应的值也就是下标和i
} //入栈,此时是[1,0]
else {
map.set(nums[i], i);/如果没有,就把这个键值对按原来的位置保存在map中,循环直到有匹配再输出
}
}
return c.pop();//出栈[0,1]
};
/*twoSum([2,7,11,15],9)
map用于存储键值对,刚开始为空
第一轮map中为空,nums[0]=2没有匹配的值.将(nums[0],0)也就是(2,0)存储进去
第二轮nums[1]=7,在map中查找发现有2,将[1,0]输出