標籤:
部落格網域名稱:http://www.xnerv.wang
原標題頁:https://oj.leetcode.com/problems/rotate-image/
題目類型:下標計算
難度評價:★★★
本文地址:http://blog.csdn.net/nerv3x3/article/details/37968757
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度順時針轉動。這種方法的缺點是要反轉兩次,長處是直觀,不easy出錯。
另外一種方法每一個元素僅僅須要調整一次,可是轉化公式會比較複雜。對於矩陣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)。
class Solution: # @param matrix, a list of lists of integers # @return nothing (void), do not return anything, modify matrix in-place instead. def rotate(self, matrix): n = len(matrix) if 1 == n: return round = int(n / 2) for x in range(0, round): for y in range(x, n - x - 1): matrix[n - y - 1][x], matrix[n - x - 1][n - y - 1], matrix[y][n - x - 1], matrix[x][y] = matrix[n - x - 1][n - y - 1], matrix[y][n - x - 1], matrix[x][y], matrix[n - y - 1][x]
著作權聲明:本文部落格原創文章,部落格,未經同意,不得轉載。
【LeetCode with Python】 Rotate Image