You are given an n x n 2D matrix representing an image.
Rotate the image by 90
degrees (clockwise).
Example
Given a matrix
[
[1,2],
[3,4]
]
rotate it by 90 degrees (clockwise), return
[
[3,1],
[4,2]
]
Challenge
Do it in-place.
public class Solution { /** * @param matrix: A list of lists of integers * @return: Void */ public void rotate(int[][] matrix) { // write your code here if(matrix == null || matrix.length <= 1) return; int n = matrix.length; for(int i = 0; i < n / 2; i++) rotate(matrix, i); return; } public void rotate(int[][] matrix, int num){ int n = matrix.length; int start = num; int end = n - 1 - num; for(int i = 0; i < end - start; i++){ int temp = matrix[start][start + i]; matrix[start][start + i] = matrix[end - i][start]; matrix[end - i][start] = matrix[end][end - i]; matrix[end][end - i] = matrix[start + i][end]; matrix[start + i][end] = temp; } return; } }
时间: 2024-11-05 18:44:08