繁体   English   中英

如何显示给定数组中两个相同数字的索引

[英]How can I show the index of two same number in a given array

我正在尝试使用参数 (number, target) 创建一个 function ,它返回给定数组中两个数字的索引,该索引等于目标的总和。 到目前为止,这是代码:

   const twoSum = function (nums, target) {

    let num1;
    let num2;
    let index1;
    let index2;

    for(let i = 0;  i < nums.length; i++){
      
        num1 = nums[i];
        num2 = target - num1;
       
        if(nums.includes(num2){
            index1 = nums.indexOf(num2);
            index2 = nums.indexOf(num1);
        }
    
    }
    return [index1, index2];
}

问题是; 当数组由相似的数字组成时,它只返回第一个数字的索引两次,例如twoSum([5,5,3], 10)返回[0,0]而不是[0,1]

我不知道你在找什么,但这会给你你所描述的。

const twoSum = function (nums, target) {

    let num1;
    let num2;
    let index1;
    let index2;

    for(let i = 0;  i < nums.length; i++) {
      
        num1 = nums[i];
        num2 = target - num1;
       
        if(nums.includes(num2)) {
            index1 = nums.indexOf(num1);
            if(num1 === num2) {
                index2 = nums.findIndex((num, i) => num === num2 && i != index1);
                if(index2 === -1) return -1; //returns -1 if no second number was found
            } else {
                index2 = nums.indexOf(num2); 
            }
            return [index1, index2]; 
        }
    
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM