LeetCode C++ 48. Rotate Image【Array】中等
发布日期:2021-07-01 02:58:15 浏览次数:2 分类:技术文章

本文共 1159 字,大约阅读时间需要 3 分钟。

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 , 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 = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Example 3:

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

Example 4:

Input: matrix = [[1,2],[3,4]]Output: [[3,1],[4,2]]

Constraints:

  • matrix.length == n
  • matrix[i].length == n
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

题意:给定一个 n × n 的二维矩阵表示一个图像。将图像顺时针旋转 90 度。


解法1 额外空间

这种做法就不写了。


解法2 常量空间

class Solution {
public: void rotate(vector
>& matrix) {
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) reverse(matrix[i].begin(), matrix[i].end()); }};

运行效率如下:

执行用时:4 ms, 在所有 C++ 提交中击败了64.58% 的用户内存消耗:7.1 MB, 在所有 C++ 提交中击败了69.34% 的用户

转载地址:https://memcpy0.blog.csdn.net/article/details/111399610 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode C++ 剑指 Offer 64. 求1+2+…+n【Bit Manipulation】中等
下一篇:LeetCode SQL 1179. Reformat Department Table【SELECT】简单

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年05月04日 00时31分37秒