通過這個你的內循環運行n/4次。它節省了時間..
傳遞| cells [0] .length/2 |的整數值。
/*********** */
for (int y=0, oddOccurLeft = cells[0].length/2,oddOccurRight = cells[0].length/2, evenOccurLeft=cells[0].length/2,evenOccurRight=cells[0].length/2; ;y++) {
if (cells[x][oddOccurLeft]) {
g.fillRect(x * cellSize, oddOccurLeft * cellSize, cellSize, cellSize);
}
if (cells[x][oddOccurRight]) {
g.fillRect(x * cellSize, oddOccurRight * cellSize, cellSize, cellSize);
}
if (cells[x][evenOccurLeft]) {
g.fillRect(x * cellSize, evenOccurLeft * cellSize, cellSize, cellSize);
}
if (cells[x][evenOccurRight]) {
g.fillRect(x * cellSize, evenOccurRight * cellSize, cellSize, cellSize);
}
***if(oddOccurLeft<0 && oddOccurRight<0 && oddOccurRight>cells[0].length && evenOccurLeft>cells[0].length && evenOccurRight>cells[0].length)
break;***
oddOccurLeft=oddOccurLeft-y*2+1;
oddOccurRight=oddOccurRight+y*2+1;
evenOccurLeft=evenOccurLeft-y*2;
evenOccurRight=evenOccurRight+y*2;
}
我懷疑你不能。如果你想遍歷二維數組,你需要兩個循環(一個循環遍歷行,另一個遍歷列)或一個循環,它將迭代x * y(假設這些長度是固定的)次,但是你還需要花費一些計算時間會告訴你你正在訪問哪一行和哪一列。也許創造其他結構,它只保留應該使用的點,而不是保持「假」的位置。 – Pshemo
是否有可能將單元格2d數組更改爲其他結構以僅保存真值? –
@Sunil Singhal問題更多的是,當我產生40000 * 40000條目的其他結構通常很慢... – TheSorm