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?
我正在使用多項式O(n ^ 2)運行時來查找所有1。然而,如果我的2維增長真的很大,這種方法將受到影響。這會耗費時間。應該使用什么算法,你能重構代碼嗎?
function findAllOnes(input) {
var s = '';
locationsOfOnes = [];
for (var y = 0; y < input.length; y++) {
s = '';
for (var x = 0; x < input[0].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/
您可以使用此實時工作代碼 - https://jsfiddle.net/tLpa1f3s/
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.
我不認為這可以比O(n ^ 2)更好地完成,因為你必須至少遍歷一次數組以獲得值等於1的位置。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/08/09/a3a569b970e951fc31c9d1fe600af0e.html。