File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Question Link: https://leetcode.com/problems/rotate-array/
3
+ * Primary idea: reverse the whole array, then reverse parts of it seperately
4
+ *
5
+ * Note: Argument of a function in Swift is let by default, so change it to var if you need to alter the value
6
+ *
7
+ * Time Complexity: O(n), Space Complexity: O(1)
8
+ *
9
+ */
10
+
11
+ class RotateArray {
12
+ func rotate( inout nums: [ Int ] , _ k: Int ) {
13
+ var k = k % nums. count
14
+
15
+ _reverse ( & nums, 0 , nums. count - 1 )
16
+ _reverse ( & nums, 0 , k - 1 )
17
+ _reverse ( & nums, k, nums. count - 1 )
18
+ }
19
+
20
+ private func _reverse( inout nums: [ Int ] , _ startIdx: Int , _ endIdx: Int ) {
21
+ // edge case
22
+ if startIdx < 0 || endIdx > nums. count || startIdx >= endIdx {
23
+ return
24
+ }
25
+
26
+ var startIdx = startIdx
27
+ var endIdx = endIdx
28
+
29
+ while startIdx < endIdx {
30
+ _swap ( & nums, startIdx, endIdx)
31
+ startIdx += 1
32
+ endIdx -= 1
33
+ }
34
+ }
35
+
36
+ private func _swap( inout nums: [ Int ] , _ p: Int , _ q: Int ) {
37
+ var temp : Int = nums [ p]
38
+ nums [ p] = nums [ q]
39
+ nums [ q] = temp
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments