Leetcode 細節實現 Rotate Image
來源:程序員人生 發布時間:2014-09-02 12:05:55 閱讀次數:3633次
本文為senlie原創,轉載請保留此地址:http://blog.csdn.net/zhengsenlie
Rotate Image
Total Accepted: 15609 Total
Submissions: 49679My Submissions
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?
題意:給定一個 n * n 的二維圖像,將該圖像順時針旋轉 90 度
思路:
先沿副對角線翻轉一次,再沿水平中線翻轉一次
復雜度:時間O(n^2),空間O(1)
void rotate(vector<vector<int> > &matrix){
int n = matrix.size();
//沿副對角線翻轉
for(int i = 0; i < n; ++i){
for(int j = 0; j < n - i; ++j){
int i2 = n - 1 - j, j2 = n - 1 - i;
swap(matrix[i][j], matrix[i2][j2]);
}
}
//沿水平中線翻轉
for(int i = 0; i < n/2; ++i){
swap(matrix[i], matrix[n - i - 1]);
}
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈