Question: https://leetcode.com/problems/rotate-array/

Question Name: Rotate Array

Classic Doug McIlroy’s Handwaving. It is very similar with some previous question.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Solution: # @param {integer[]} nums # @param {integer} begin, inclusive # @param {integer} end, exclusive # @return {void} Do not return anything, reverse array in-place. def reverse(self, nums, begin, end): for index in xrange((end - begin) // 2): front = begin + index back = end - index - 1 nums[begin + index] ^= nums[end - index - 1] nums[end - index - 1] ^= nums[begin + index] nums[begin + index] ^= nums[end - index - 1] return # @param {integer[]} nums # @param {integer} k # @return {void} Do not return anything, modify nums in-place instead. def rotate(self, nums, k): k = len(nums) - (k % len(nums)) if k != len(nums): self.reverse(nums, 0, k) self.reverse(nums, k, len(nums)) self.reverse(nums, 0, len(nums)) return |