Leetcode95: Rotate Image
来源:互联网 发布:c语言二维数组初始化 编辑:程序博客网 时间:2024/04/29 14:00
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?
举一个二维数组变换的例子就知道变换的坐标由a[i][j]->a[j][n-1-i]
最笨的办法就是复制数组然后再重新赋值
class Solution {public: void rotate(vector<vector<int>>& matrix) { int n = matrix.size(); vector<vector<int> > tmp(n, vector<int>(n)); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { tmp[i][j] = matrix[i][j]; } } for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { matrix[j][n-1-i] = tmp[i][j]; } } }};然后在网上看到一个技巧,把数组先沿着中间一行上下对调,然后沿着对角线对调即可,不用开辟新的空间存储。
class Solution {public: void rotate(vector<vector<int>>& matrix) { int n = matrix.size(); int tmp; for(int i = 0; i < n/2; i++) { for(int j = 0; j < n; j++) { tmp = matrix[i][j]; matrix[i][j] = matrix[n-1-i][j]; matrix[n-1-i][j] = tmp; } } for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { tmp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = tmp; } } }};
0 0
- Leetcode95: Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Unity 3D 萌萌哒三消游戏《宝石消消乐》完整源码
- android多媒体的一些问题
- set容器(如何判断set.insert()函数的返回值)
- 【基础练习】【贪心】codevs2612 最优分解方案题解
- 八款android日历 [Calendar] 开源项目框架分类总汇
- Leetcode95: Rotate Image
- 快速排序算法
- JSON.parse()和JSON.stringify()
- javascript 字符串操作
- Mac新手入门
- centos 安装 Consolas 字体
- WebView简单使用
- 插入排序算法 —— 直接插入排序
- IOS推送声音