【Leetcode】48. 旋轉圖像(Rotate Image)

Leetcode - 48 Rotate Image (Medium)

題目描述:將一個 n × n 的矩陣旋轉 90°,不能使用額外的輔助空間。

Given input matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

解題思路:原地旋轉,這個時候就需要找規律了,規律:先左右交換,在以對稱軸(斜上)交換。

public void rotate(int[][] matrix) {
    for(int i = 0; i<matrix.length; i++){
        for(int j = i; j<matrix[0].length; j++){
            int temp = 0;
            temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }
    for(int i =0 ; i<matrix.length; i++){
        for(int j = 0; j<matrix.length/2; j++){
            int temp = 0;
            temp = matrix[i][j];
            matrix[i][j] = matrix[i][matrix.length-1-j];
            matrix[i][matrix.length-1-j] = temp;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章