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:
[1,2,3,4,5,6,7]
K[5,6,7,1,2,3,4]
[7,1,2,3,4,5,6]
[6,7,1,2,3,4,5]
[5,6,7,1,2,3,4]
Example 2:
[-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:defrotate (self, nums, K):""": Type Nums:list[int]: type k:int:rtype:void do not return anything, modify Nums in-place ins Tead. """ ifK = = 0orLen (Nums) < 2: returnlength=Len (nums) n, I, J=0, 0, 0 temp1=Nums[0] whileN <length:j= (j + k)%length Temp2=Nums[j] Nums[j]=Temp1 Temp1=Temp2ifi = =j:i= (i + 1)%Length J=I temp1=Nums[i] n+ = 1
Rotating an array