48. Rotate Image

LeetCode 48. Rotate Image****

Description

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.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

Example 2:

Input: matrix = [[1]]
Output: [[1]]

Tags

Array

Solution

  1. Transpose the matrix (Note: the inner loop is start from the position of the outer loop);

  2. Flip the matrix horizontally.

Complexity

  • Time complexity: O(n2)O(n^2)

  • Space complexity: O(1)O(1)

Code

func rotate(matrix [][]int) {
	for i := 0; i < len(matrix); i++ {
		for j := i; j < len(matrix[0]); j++ {
			matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
		}
	}
	for i := 0; i < len(matrix); i++ {
		for l, r := 0, len(matrix[i])-1; l < r; l, r = l+1, r-1 {
			matrix[i][l], matrix[i][r] = matrix[i][r], matrix[i][l]
		}
	}
}

Last updated

Was this helpful?