簡體   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