Skip to content

Commit 11b9f09

Browse files
committed
Time: 502 ms (42.64%), Space: 72 MB (18.02%) - LeetHub
1 parent 817ae41 commit 11b9f09

File tree

1 file changed

+21
-9
lines changed

1 file changed

+21
-9
lines changed

rotate-array/rotate-array.kt

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,27 @@
11
class Solution {
22
fun rotate(nums: IntArray, k: Int): Unit {
3-
val map = HashMap<Int, Int>()
4-
nums.forEachIndexed{ index, value ->
5-
map.put((index+k) % nums.size, value)
6-
}
73

8-
nums.forEachIndexed{ index, value ->
9-
map[index]?.let{
10-
nums[index] = it
11-
}
12-
4+
5+
var rotateCount = k % nums.size
6+
reverseArray(0, nums.size - 1, nums)
7+
reverseArray(0, rotateCount - 1, nums)
8+
reverseArray(rotateCount, nums.size - 1, nums)
9+
10+
}
11+
12+
13+
fun reverseArray(startIndex: Int, endIndex: Int, nums: IntArray){
14+
15+
var left = startIndex
16+
var right = endIndex
17+
18+
while(left < right){
19+
var first = nums[left]
20+
var second = nums[right]
21+
nums[left++] = second
22+
nums[right--] = first
1323
}
24+
1425
}
26+
1527
}

0 commit comments

Comments
 (0)