48. Rotate Image
題目網址:https://leetcode.cn/problems/rotate-image/
題意:給一
n x n
的 2D array 表示一個 image, 請將 image 順時針旋轉 90 度。注意:請使用 in-place 演算法
Solution 1:
想法:將
matrix
由外而內分成好幾層, 每一層依序交換以完成旋轉
class Solution { |
- time:$O(n^2)$ ➔ 遍歷
matrix
- space:$O(1)$ ➔ 只需常數空間
Solution 2:(進階)
想法:先將
matrix
做轉置(將同 row 的元素變成同 col), 然後再每列做水平翻轉(reverse)
(水平翻轉:原本左邊 $1^{st}$ col 變成右邊 $1^{st}$ col, 左邊 $2^{nd}$ col 變成右邊 $2^{nd}$ col, 依此類推)
class Solution { |
- time:$O(n^2)$ ➔ 遍歷
matrix
- space:$O(1)$ ➔ 只需常數空間
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Zako's Blog!
評論