【发布时间】:2015-04-08 16:52:46
【问题描述】:
我有一个程序需要从byte[][] 数组中删除一组行。我想删除其中没有零的每一行。现在我正在使用以下方法:
public byte[][] checkRows(byte[][] grid) {
LinkedList<Integer> temp = new LinkedList<Integer>();
boolean willRemove = false;
for (int y = 0; y < grid.length; y++) {
boolean tempCheck = true;
for (int x = 0; x < grid[0].length; x++) {
if (grid[y][x] == 0) {
tempCheck = false;
break;
}
}
if (tempCheck) {
temp.add(y);
willRemove = true;
}
}
if (willRemove) {
int[] rowArray = convert(temp);
return removeRows(grid, rowArray);
}
return grid;
}
public byte[][] removeRows(byte[][] grid, int[] rows) {
int total = rows.length;
int current = 0;
byte[][] retGrid = new byte[grid.length][grid[0].length];
for (int i = total; i < grid.length; i++) {
if (current < total && i-total+current == rows[current]) {
current++;
}
//retGrid[i] = grid[i-total+current].clone();
System.arraycopy(grid[i-total+current], 0, retGrid[i], 0, xsize);
}
return retGrid;
}
public int[] convert(LinkedList<Integer> intList) {
int[] retArray = new int[intList.size()];
for (int i = 0; i < retArray.length; i++) {
retArray[i] = intList.get(i).intValue();
}
return retArray;
}
这为我提供了一种从 2D 数组中删除行并用数组顶部的零行替换它们的相当快速的方法。有没有更快的方法来达到同样的效果?
如果不清楚脚本的作用,它是用于删除俄罗斯方块游戏中的完整行。
更新:使用 System.arraycopy() 代替 clone() 可为小型数组提供 5% 的性能提升。
【问题讨论】:
标签: java arrays optimization arraylist clone