2.1.16 Rotate Image

Link: https://oj.leetcode.com/problems/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?

Time: O(n^2), Space: O(1)

一次過。不用再寫。

public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        for(int i = 0; i < n/2; i++){
            for(int j = 0; j < n; j++){
                int tmp = matrix[i][j];
                matrix[i][j] = matrix[n-1-i][j];//n-1-i, not n-i
                matrix[n-1-i][j] = tmp;
            }
        }
        for(int i = 0; i < n; i++){
            for(int j = i+1; j < n; j++){//j starts from i+1, not 0 (i.e. Upperleft triangle)
                int tmp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = tmp;
            }
        }
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章