48. Rotate Image
来源:互联网 发布:java sessionscoped 编辑:程序博客网 时间:2024/05/29 19:08
题目:
原题链接:https://leetcode.com/problems/rotate-image/
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
给出一个n x n的矩阵,把它按顺时针旋转90度。
为了效率尽可能的高,应该尽量用最少的次数把它旋转到位。
假设矩阵每一层的可以看成四条边,分别是上,下,左,右。
那么顺时针旋转90度可以看成是上换到右,右换到下,下换到左。
然后再细分到每条边的每一个元素。由于每条边上都可以看成是对应位偏移上的元素之间互换,所以只需要看上这条边的元素就可以了。
假设现在旋转上这条边的第 i 个元素,那么它应该换到右边从上倒下第 i 个元素的位置上;
原来右边从上到下的第 i 个元素要换到下边从右到左的第 i 个元素上;
原来下边从右到左的第 i 个元素要换到左边从下到上的第 i 个元素上;
原来左边从下到上的第 i 个元素要换到上边从左到右的元素位置上。
更简单一点的做法是:
交换上边的从左到右第 i 个元素和右边的从上到下第 i 个元素;
交换上边的从左到右第 i 个元素和左边的从下到上第 i 个元素;
交换左边的从下到上第 i 个元素和下边的从右到左第 i 个元素;
按照上面的思路,每次选择矩阵每一层的的上边,对上边的每一个元素进行上述的交换即可。
代码如下:
class Solution {public: void change(vector<vector<int>>& matrix, int len, int i, int offset) { swap(matrix[i][i + offset], matrix[i + offset][len - 1 - i]); swap(matrix[i][i + offset], matrix[len - 1 - i - offset][i]); swap(matrix[len - 1 - i - offset][i], matrix[len - 1 - i][len - 1 - i - offset]); } void rotate(vector<vector<int>>& matrix) { int len = matrix.size(); for(int i = 0; i < len / 2; ++i) { for(int j = i; j < len - i - 1; ++j) { change(matrix, len, i, j - i); } } return; }};
0 0
- [LeetCode]48.Rotate Image
- LeetCode 48. Rotate Image
- LeetCode 48.Rotate Image
- LeetCode --- 48. Rotate Image
- [Leetcode] 48. Rotate Image
- 48. Rotate Image
- 48. Rotate Image
- 48. Rotate Image
- 48. Rotate Image
- [leetcode] 48. Rotate Image
- Leetcode 48. Rotate Image
- 48. Rotate Image LeetCode
- [LeetCode]48. Rotate Image
- 48. Rotate Image
- 48. Rotate Image
- leetcode 48. Rotate Image
- Leetcode 48. Rotate Image
- LeetCode 48. Rotate Image
- MIT牛人解说数学体系
- 【数论】乘法逆元
- easyUI中textArea控制输入字符的多少
- xml介绍
- $.ajax $.getJSON在java中的跨越解决方案
- 48. Rotate Image
- Activity简单几步支持向右滑动返回
- char类型和int型可以通用
- 声学模型学习笔记(三) DNN-HMM hybrid system
- 第十五节:集合框架一(个人总结)
- UVA 11825 Hacker's Crackdown(状压dp)
- 一维数组巩固,二维数组的学习
- 【HDU】5746 Memento Mori【双指针】
- PullRefresh(自定义控件,ListView,下拉刷新,加载更多)