LC两数之和 JS

LC两数之和 JS

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。

示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

链接:https://leetcode.cn/leetbook/read/top-interview-questions-easy/x2jrse/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

var twoSum = function(nums, target) {
    
    
   var i=0;
    while(i<nums.length){
    
    
        var next = target-nums[i];
        for(var j=i+1;j<nums.length;j++){
    
    
            if(nums[j]==next){
    
    
                return [i,j];
            }
        }
        i++;
    }
 };
var twoSum = function(nums, target) {
    
    
   for(let i=0;i<nums.length;i++){
    
    
        var next = target-nums[i];
        for(let j=i+1;j<nums.length;j++){
    
    
            if(nums[j]==next){
    
    
                return [i,j];
            }
        }
    }
};
var twoSum = function(nums, target) {
    
    
        var map = new Map();
        for(let i=0;i<nums.length;i++){
    
    
        let x=target-nums[i];
        if(map.has(x)){
    
    
            return([map.get(x),i])
        }
        map.set(nums[i],i)
    }
};

猜你喜欢

转载自blog.csdn.net/m0_47147246/article/details/126078215
今日推荐