Given an array, move the elements in the array to the right by the K position, where K is a non-negative number.
Example 1:
Input: [1,2,3,4,5,6,7]
k = 3 output: [5,6,7,1,2,3,4]
Explanation:[7,1,2,3,4,5,6]
[6,7,1,2,3,4,5]
[5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99]
k = 2 output: [3,99,-1,-100] Explanation: Rotate Right 1 steps: [99,-1,-100,3] Rotate Right 2 steps: [3,99,-1,-100]
Description
- Think of as many solutions as possible, at least three different ways to solve the problem.
- Requires an in-place algorithm with a space complexity of O (1).
classSolution:def __reverse(self,nums,start,end): while(Start <end): Nums[start],nums[end]=Nums[end],nums[start] Start+ = 1End-= 1defrotate (self, nums, K):""": Type Nums:list[int]: type k:int:rtype:void do not return anything, modify Nums in-place ins Tead. """k%=Len (nums) self.__reverse(Nums,0,len (nums)-1) self.__reverse(nums,0,k-1) self.__reverse(Nums,k,len (Nums)-1)
"Leetcode Simple" the 47th question rotating an array