博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【一天一道LeetCode】#48. Rotate Image
阅读量:4197 次
发布时间:2019-05-26

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

一天一道LeetCode系列

(一)题目

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:

Could you do this in-place?

(二)解题

90度旋转图像,我们不难看出

matrix[i][j]=tmp[j][ni1]:tmp=matrix
经过这样的变换后,图像就旋转了90度。

class Solution {public:    void rotate(vector
>& matrix) { int n = matrix.size()-1; vector
> tmp = matrix;//深拷贝 for(int i = 0 ; i< n+1; i++) { for(int j = 0 ; j < n+1 ; j++) { matrix[j][n-i] = tmp[i][j];//赋值转换 } } }};

网上还有一种解法去先转置在对称变换。代码如下:

class Solution {public:    void rotate(vector
> &matrix) { int dim = matrix.size(); int temp = 0; for (int i = 0; i < dim; ++i) { //先转置 for (int j = i+1; j < dim; ++j) { temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } for (int i = 0; i < dim/2; ++i) { //然后对称变换 for (int j = 0; j < dim; ++j) { temp = matrix[j][i]; matrix[j][i] = matrix[j][dim - i -1]; matrix[j][dim - i -1] = temp; } } }};

转载地址:http://sayli.baihongyu.com/

你可能感兴趣的文章
【计算机网络 第五版】阅读笔记之一:概述
查看>>
【计算机网络 第五版】阅读笔记之二:物理层
查看>>
【计算机网络 第五版】阅读笔记之三:数据链路层
查看>>
【计算机网络 第五版】阅读笔记之四:网络层
查看>>
【计算机网络 第五版】阅读笔记之五:运输层
查看>>
【一天一道LeetCode】#77. Combinations
查看>>
【一天一道LeetCode】#78. Subsets
查看>>
【一天一道LeetCode】#79. Word Search
查看>>
【一天一道LeetCode】#81. Search in Rotated Sorted Array II
查看>>
【数据结构与算法】深入浅出递归和迭代的通用转换思想
查看>>
【一天一道LeetCode】#83. Remove Duplicates from Sorted List
查看>>
【一天一道LeetCode】#91. Decode Ways
查看>>
【一天一道LeetCode】#92. Reverse Linked List II
查看>>
【一天一道LeetCode】#93. Restore IP Addresses
查看>>
【一天一道LeetCode】#94. Binary Tree Inorder Traversal
查看>>
【一天一道LeetCode】#112. Path Sum
查看>>
【一天一道LeetCode】#113. Path Sum II
查看>>
【一天一道LeetCode】#114. Flatten Binary Tree to Linked List
查看>>
【unix网络编程第三版】阅读笔记(二):套接字编程简介
查看>>
【一天一道LeetCode】#115. Distinct Subsequences
查看>>