【LeetCode with Python】 Rotate Image,leetcoderotate

來源:互聯網
上載者:User

【LeetCode with Python】 Rotate Image,leetcoderotate

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度轉動一個二維矩陣,要求in-place的演算法,也就不是不能另外開一個新的矩陣然後把原矩陣上的元素一個個對應複製過來,而要在原矩陣上進行操作。

演算法分析:
目前能想到的有兩種方法。
第一種比較直觀,首先將原矩陣按照水平軸上下翻轉,然後按照左上到右下的對角線再反轉,則等價於90度順時針轉動。這個方法的缺點是要反轉兩次,優點是直觀,不容易出錯。
第二種方法每個元素只需要調整一次,但是轉化公式會比較複雜。對於矩陣matrix[n][n]中的某一點matrix[x][y](0<=x, y<n),90度順時針轉動後到了matrix[y][n-x-1],而matrix[y][n-x-1]到了matrix[n-x-1][n-y-1],matrix[n-x-1][n-y-1]到了matrix[n-y-1][x],matrix[n-y-1][x]又到了matrix[x][y],可見這四個點正好實現了一次旋轉互換。
本文採用第二種方法,空間複雜度O(1),時間複雜度O(n*n)。

防坑警報:
n=1時直接返回原矩陣即可。


python withas

with open('abc.txt', 'r') as f:
balabalabala

等價於
try:
f = open('abc.txt', 'r')
except:
pass
else:
balabalabala
finally:
f.close()
文法是不是簡潔多了?
 
A Primer on Scientific Programming with Python 中文版

推薦盡量看英文的,第一手資料
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.