當前位置:
首頁 >
【Leetcode】【Medium】Rotate Image
發布時間:2024/10/12
55
豆豆
生活随笔
收集整理的這篇文章主要介紹了
【Leetcode】【Medium】Rotate Image
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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?
解題思路1,時間復雜度o(n):
順時針旋轉的規律很好找到,為了完全在矩陣內部操作,普通的辦法就是每遍歷到一個位置,則將與這個位置相關的一周(旋轉一周涉及到的4個位置)都進行替換操作。
代碼:
1 class Solution { 2 public: 3 void rotate(vector<vector<int>>& matrix) { 4 int n = matrix.size() - 1; 5 for (int i = 0; i <= n / 2; ++i) { 6 for (int j = i; j < n - i; ++j) { 7 int reserve = matrix[i][j]; 8 int p = 4; 9 while (p--) { 10 if (p == 0) 11 matrix[i][j] = reserve; 12 else 13 matrix[i][j] = matrix[n-j][i]; 14 int tmp = i; 15 i = n - j; 16 j = tmp; 17 } 18 } 19 } 20 return; 21 } 22 };?
解題思路2,時間復雜度o(n):
拿出一張正方型紙,將紙順時針旋轉90度,相當于先將紙向后反轉180度,再以左上-右下對角線為軸,旋轉180度。
所以,本題類似思路,先將矩陣按行反轉,在按左上-右下對角線為軸,做兩兩映射交換。
1 class Solution { 2 public: 3 void rotate(vector<vector<int>>& matrix) { 4 reverse(matrix.begin(), matrix.end()); 5 for (int i = 0; i < matrix.size() - 1; ++i) { 6 for (int j = i; j < matrix.size(); ++j) { 7 swap(matrix[i][j], matrix[j][i]); 8 } 9 } 10 return; 11 } 12 };?
轉載于:https://www.cnblogs.com/huxiao-tee/p/4338766.html
總結
以上是生活随笔為你收集整理的【Leetcode】【Medium】Rotate Image的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 装了显卡电脑很卡怎么回事 电脑装了显卡后
- 下一篇: JVM调优总结 -Xms -Xmx -X