[48] leetcode rotated image (array, in-place algorithm)

Topic links: https://leetcode-cn.com/problems/rotate-image/

Title Description

Given an n × n represents a two-dimensional matrix image.

The image is rotated 90 degrees clockwise.

Description:

You have to rotate the image in place, which means you need to directly modify the two-dimensional matrix input. Do not use another matrix to rotate an image.

Example 1:

给定 matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

原地旋转输入矩阵,使其变为:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

Example 2:

给定 matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

原地旋转输入矩阵,使其变为:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]

Thinking

A mirror symmetric transpose +

Complexity Analysis

  • Time complexity: O (n ^ 2)
  • Space complexity: O (1)
/*
 * 转置+镜像对称
 * 时间复杂度O(N^2)
 */
class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        if(matrix.empty() || matrix[0].empty() || matrix.size() == 1) return;
        int n = matrix.size();
        // 转置
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < i; ++j) {
                swap(matrix[i][j], matrix[j][i]);
            }
        }
        // 镜像对称
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n/2; ++j) {
                swap(matrix[i][j], matrix[i][n-1-j]);
            }
        }
    }
};

Here Insert Picture Description

2 is rotated rectangle

/*
 * 遍历每一圈
 * 四个边的元素顺时针转
 * 每个元素访问一遍,时间复杂度O(N^2)
 */
class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        if(matrix.empty() || matrix[0].empty() || matrix.size() == 1) return;
        int n = matrix.size();
        for (int i = 0; i < n/2; ++i) {
            int begin = i;
            int end = n - i -1;
            for (int j = 0; j < end - begin; ++j) {
                int tmp = matrix[begin][begin+j];   // 左上
                matrix[begin][begin+j] = matrix[end -j][begin]; // 左上=左下,上=左
                matrix[end-j][begin] = matrix[end][end-j];      // 左下=右下,左=下
                matrix[end][end-j] = matrix[begin+j][end];      // 右下=右上,下=右
                matrix[begin+j][end] = tmp;                     // 右上=左上,右=上
            }
        }
    }
};

Complexity Analysis

  • Time complexity: O (n ^ 2)
  • Space complexity: O (1)

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/zjwreal/article/details/94601501
Recommended