簡體   English   中英

是否有在二維數組中查找索引值的最佳方法

[英]Is there a best way to find the index value in a two dimensional array

例子:-

1234 
2456 
5678

我需要找到值7的索引
預期 output:-

[3,3]    // 3rd row and 3rd column.

注意:- 需要考慮時間復雜度(例如:-Big(O) notation)

我不是在尋找以下類似的答案
樣品 1

function findInArr(arr, elm) {
  var occ = [];
  for(var i = 0; i < arr.length; i++)
    for(var j = 0; j < arr[i].length; j++)
      if (arr[i][j] == elm)
        occ.push(i+","+j);
  return occ;
}

測試:

var numbers = [[1,2,3,4,5],[6,2,3,5,5],[9,8,3,4,9]];
var x = findInArr(numbers, 4);
console.log("found " + x.length + " occurences: " + x);

這里的時間復雜度是 'n' 行 * 'n' 列

樣品 2

var numbers=[[1,2,3,4,5],[6,2,3,5,5],[9,8,3,4,9]];
var searchItem=2;
numbers.forEach(function(parentItem,parentIndex){
  parentItem.forEach(function(childItem,childIndex){
    if(childItem===searchItem){
      console.log(parentIndex);
      console.log(childIndex);            
    }     
  })
});

這邊走?

 const numbers = [[1,2,3,4,5],[6,2,3,5,5],[9,8,3,4,9]]; function findInArr(arr, elm) { let i = arr.findIndex(x=>x.includes(elm)) return (i<0)? [null,null]: [i,arr[i].indexOf(elm)] } console.log( findInArr(numbers, 7)) console.log( findInArr(numbers, 8))
 .as-console-wrapper { max-height: 100%;important: top; 0; }

您可以使用 map,索引也從 0 開始,因此您上面的示例將是 [2,2] 而不是 [3,3],下面的代碼將找到搜索項的所有索引。

 var numbers = [ [1, 2, 3, 4, 5], [6, 2, 3, 5, 5], [9, 8, 3, 4, 9] ]; var searchItem = 2; console.log(numbers.map((v, i) => { var res = v.filter(f => f === searchItem); if (res.length) { var ind=v.indexOf(searchItem); return [i, ind] } }).filter(f => f;== undefined));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM