48. Rotate Image

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?

一刷
题解:
坐标的变换为:
(i, j)->(j, n-1-i)->(n-1-i, n-1-j)->(n-1-j, i)->(i, j)

此时,注意i和j的范围
当n为偶数时,i,j的范围相同;
当n为奇数时,i比j最大值大1,则中线上的值只变动一次,避免产生冲突。(或者j比i最大值大1)

48. Rotate Image_第1张图片
public class Solution {
    public void rotate(int[][] matrix) {
        //(i, j)->(j, n-1-i)->(n-1-i, n-1-j)->(n-1-j, i)->(i, j)
        int n=matrix.length;
        if(matrix == null) return;
        for(int i=0; i<(n+1)/2; i++){
            for(int j=0; j

你可能感兴趣的:(48. Rotate Image)