MrainW's Home

All things come to those who wait!

0%

LeetCode 48. Rotate Image

Question

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

https://leetcode.com/problems/rotate-image/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public void rotate(int[][] matrix) {
if (matrix == null) return;
if (matrix.length == 0 || matrix[0].length == 0) return;
int top = 0;
int left = 0;
int right = matrix.length - 1;
int bottom = matrix.length - 1;
int n = matrix.length;
while (n > 1) {
for (int i = 0; i < n - 1; i++) {
int tmp = matrix[top][left + i];
matrix[top][left + i] = matrix[bottom - i][left];
matrix[bottom - i][left] = matrix[bottom][right - i];
matrix[bottom][right - i] = matrix[top + i][right];
matrix[top + i][right] = tmp;
}
top++;
bottom--;
left++;
right--;
n -= 2;
}
}
}

Complexity:

Time complexity: O(n^2)

Space complexity: O(1)

Welcome to my other publishing channels