two sum

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]输出

map含义和用法:https://www.cnblogs.com/goloving/p/7979423.html

https://blog.csdn.net/chauncywu/article/details/73302353 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值