public class Solution { public void reverse(int[] nums, int start, int end) { while (start < end) { int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } } public void Rotate(int[] nums, int k) { k %= nums.Length; reverse(nums, 0, nums.Length - 1); reverse(nums, 0, k - 1); reverse(nums, k, nums.Length - 1); }}
补充一个python的实现:
1 class Solution: 2 def rotate(self, nums: List[int], k: int) -> None: 3 """ 4 Do not return anything, modify nums in-place instead. 5 """ 6 n = len(nums) 7 part1 = nums[n-k:] 8 part2 = nums[:n-k] 9 nums.clear()10 nums.extend(part1)11 nums.extend(part2)