### 使用javascript在2-dim數組中查找元素的最有效方法

#### [英]Most efficient way to find an element in a 2-dim array using javascript

I'm using polynomial O(n^2) runtime to find all 1s. However, this approach would suffer if my 2 dimensional grow real big. It's going to eat up time. What algorithm should be used and can you refactor the code?

``````function findAllOnes(input) {
var s = '';
locationsOfOnes = [];
for (var y = 0; y < input.length; y++) {
s = '';
for (var x = 0; x < input.length; x++) {
s = s + input[y][x].toString(); // this is just for output to show it in 2 dimensional view
if (input[y][x] !== 0) {
locationsOfOnes.push({x: x, y: y})
}
}
console.log(y.toString() + '.)', s)
}
return locationsOfOnes;
}
``````

You can use this live working code - https://jsfiddle.net/tLpa1f3s/

## 1 个解决方案

### #1

2

I don't think this can be done better than O(n^2) since you would have to travel traverse the array at least once in order to get where the value is equal to one.

#### 注意！

© 2014-2022 ITdaan.com 联系我们： 