标签:面试 leetcode algorithm 旋转 数组
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°。这个题也是个没啥意思的题,自己画画图,找找规律。就出来了。我举一个n=4的例子还说明下规律:
通过图可以看出A[0][0] = A[3][0],....。从这些中我们可以找到如下规律:
A[i][j] = A[n-1-j][i];
A[n-1-j][i] = A[n-1-i][n-1-j];
A[n-1-i][n-1-j] = A[j][n-1-i];
A[j][n-1-i] = A[i][j];(原来的A[i][j]).
规律出来了,代码也就好写了,不过的考虑边界的情况。这个自己还得举个n为奇数的例子看看。
class Solution { public: void rotate(vector<vector<int> > &A) { int m = A.size(); if(m<=0) return ; int n = A[0].size(); for(int i=0; i<m/2;++i){ for(int j=i; j<n-1-i; ++j){ int temp = A[i][j]; A[i][j] = A[n-1-j][i]; A[n-1-j][i] = A[n-1-i][n-1-j]; A[n-1-i][n-1-j] = A[j][n-1-i]; A[j][n-1-i] = temp; } } } };
[LeetCode] Rotate Image [26],布布扣,bubuko.com
标签:面试 leetcode algorithm 旋转 数组
原文地址:http://blog.csdn.net/swagle/article/details/29810515