题目描述
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
- 思路
顺时针90°旋转 n*n 的矩阵。
法一:利用临时数组保留原二维数组的值。由题可把第 i 行依次放在第 n-i-1 列里,i++循环放置即可。
法二:不使用额外空间。按对角线翻转数组后,再沿中线翻转
复制数组的方法
① public static void native arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
src:原对象
srcPos:原对象起始位置
dest:目标对象
destPos:目标对象起始位置
length:复制的长度
(System.arraycopy(...))
.
② protected native Object clone() throws CloneNotSupportedException;
注意返回的对象要强转
.
③ java.util.Arrays.Arrays.copyOf(源数组, 新数组长度);
java.util.Arrays.copyOfRange(源数组, 开始拷贝位置, 结束拷贝位置);
数组类型含多种,详情见API
.
具体使用见代码
//第一种方法
import java.util.*;
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
int[][] temp = new int[n][n];
for(int i=0; i<n; i++){
//System.arraycopy(matrix[i], 0, temp[i], 0, n);
//temp[i] = (int[])matrix[i].clone();
temp[i] = Arrays.copyOf(matrix[i], n);
}
for(int i=n-1,u=0; i>=0; i--,u++){
for(int j=0,v=0; j<n; j++,v++){
matrix[j][i] = temp[u][v];
}
}
}
}
//第二种方法
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
//沿对角线翻转,左下角到右上角
for(int i=0; i<n; i++){
for(int j=0; j<n-i; j++){
int t = matrix[i][j];
matrix[i][j] = matrix[n-j-1][n-i-1]; //注意坐标
matrix[n-j-1][n-i-1] = t;
}
}
//沿中线翻转
for(int i=0; i<n/2; i++){
for(int j=0; j<n; j++){
int t = matrix[i][j];
matrix[i][j] = matrix[n-i-1][j];
matrix[n-i-1][j] = t;
}
}
}
}