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
// @Title: 旋转数组 (Rotate Array)
// @Author: 15816537946@163.com
// @Date: 2021-01-09 10:32:40
// @Runtime: 4 ms
// @Memory: 3.1 MB
func rotate(nums []int, k int) {
	// 我已经假定 k >= 0

	n := len(nums)

	if k > n {
		k %= n
	}
	if k == 0 || k == n {
		return
	}

	reverse(nums, 0, n-1)
	reverse(nums, 0, k-1)
	reverse(nums, k, n-1)
}

func reverse(nums []int, i, j int) {
	for i < j {
		nums[i], nums[j] = nums[j], nums[i]
		i++
		j--
	}
}