【发布时间】:2019-12-24 18:20:15
【问题描述】:
我确实遇到了一个著名的面试问题,其中给了我们一个二维数组,我们需要将数组旋转 90 度,虽然有很多方法可以解决这个问题,但我决定使用一种有效的方法我们会做这样的事情。
/* * 顺时针旋转 * 先从上往下反转,然后交换对称性 * 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3 9 6 3 */上述方法的代码是:
public void rotate(int[][] matrix) {
int s = 0, e = matrix.length - 1;
while(s < e){
int[] temp = matrix[s];
matrix[s] = matrix[e];
matrix[e] = temp;
s++; e--;
}
for(int i = 0; i < matrix.length; i++){
for(int j = i+1; j < matrix[i].length; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
我主要担心的是我在第一个 while 循环中使用的数组可能会使空间复杂度 O(n)。如果我只是这样做:
int[] temp;
while( s < e ){
temp = matrix[s];
}
现在是空间复杂度 O(1) 还是保持不变?
【问题讨论】:
标签: java arrays performance matrix space-complexity