rotate-array

This commit is contained in:
Gleb Koval 2021-11-07 20:06:26 +00:00
parent 044576d006
commit 6a0a9e2b9a
No known key found for this signature in database
GPG Key ID: DF27F6A77C48FDA0
1 changed files with 19 additions and 0 deletions

19
rotate-array/sol.go Normal file
View File

@ -0,0 +1,19 @@
package main
// Time: O(n)
// Space: O(1) (original array modified)
func rotate(nums []int, k int) {
c, a, l, idx, num := 0, 0, len(nums), 0, nums[0]
for c != l {
if idx == a && c != 0 {
a++
idx = a
num = nums[idx]
}
new_idx := (idx + k) % l
old_num := nums[new_idx]
nums[new_idx] = num
idx, num = new_idx, old_num
c++
}
}