旋转图像
Math is crucial In some cases。
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
我的( 20 ms )
func rotate(_ matrix: inout [[Int]]) { var sub:Int = 0 let len=matrix.count for i in 0..<len { for j in i+1..<len { sub=matrix[i][j] matrix[i][j]=matrix[j][i] matrix[j][i]=sub } matrix[i].reverse() } }
先对数组进行转置,然后倒叙行就完成了,注意第二个循环
for j in i+1..<len
16 ms
func rotateImage1(_ matrix: inout [[Int]]) { let n = matrix.count for i in 0..<n/2 { for j in i..<(n - 1 - i) { let tmp = matrix[i][j] matrix[i][j] = matrix[n - 1 - j][i] matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j] matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i] matrix[j][n - 1 - i] = tmp } } }
对于当前位置,计算旋转后的新位置,然后再计算下一个新位置,第四个位置又变成当前位置了,所以这个方法每次循环换四个数字。
1 2 3 7 2 1 7 4 1 4 5 6 -> 4 5 6 -> 8 5 2 7 8 9 9 8 3 9 6 3
还有一种
func rotate(_ matrix: inout [[Int]]) { let n = matrix.count for i in 0..<(n - 1) { for j in 0..<(n - i) { let temp = matrix[i][j] matrix[i][j] = matrix[n - 1 - j][n - 1 - i] matrix[n - j - 1][n - i - 1] = temp } } for i in 0..<n/2 { for j in 0..<n { let temp = matrix[i][j] matrix[i][j] = matrix[n - 1 - i][j] matrix[n - 1 - i][j] = temp } } }
首先以从对角线为轴翻转,然后再以x轴中线上下翻转即可得到结果