Post

Leetcode - 189. Rotate Array

Leetcode - 189. Rotate Array

Hits

  • Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func rotate(nums []int, k int)  {
    ln := len(nums)
    if ln ==0{
        return
    }
    k = k%ln

    ReverseArray(nums, 0, ln-1)
    ReverseArray(nums, k, ln-1)
    ReverseArray(nums, 0, k-1)
}

func ReverseArray(data []int, start int, end int){
    for start<end{
        data[start], data[end] = data[end], data[start]
        start++
        end--
    }
}
This post is licensed under CC BY 4.0 by the author.