forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotateImage.swift
43 lines (34 loc) · 1.12 KB
/
RotateImage.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Question Link: https://leetcode.com/problems/rotate-image/
* Primary idea: Go from clockwise and from outside to inside, use offset for convenience
*
* Time Complexity: O(n^2), Space Complexity: O(1)
*/
class RotateImage {
func rotate(inout matrix: [[Int]]) {
let n = matrix.count
guard n > 0 else {
return
}
var start = 0
var end = 0
var offset = 0
var temp = 0
for layer in 0 ..< n / 2 {
start = layer
end = n - 1 - layer
for i in start ..< end {
offset = i - start
temp = matrix[start][i]
// left -> top
matrix[start][i] = matrix[end - offset][start]
// bottom -> left
matrix[end - offset][start] = matrix[end][end - offset]
// right -> bottom
matrix[end][end - offset] = matrix[i][end]
// top -> right
matrix[i][end] = temp
}
}
}
}