Rotate an array of n elements to the right by K steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] was rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as can, there is at least 3 different ways to solve this problem.
Thought:
1.-567 Rotation-765
2.-1234 Rotation-4321
3.-Overall rotation 4321765-5671234
Solution:
voidReverseintLeftintRightint*Array){inttemp =0; while(Left<right) {temp =Array[Left];Array[left]=Array[Right];Array[Right] = temp; left++; right--; }}voidRotateint* Nums,intNumssize,intK) {k = k%numssize;//Don't know why this sentence is added here? Reverse0, numssize-k-1, nums); Reverse (numssize-k,numssize-1, nums); Reverse0, numssize-1, nums);}
Python solution:
class solution:# @param nums, a list of integers# @param k, num of steps# @return Nothing, please modify the Nums list in-place. def rotate(self, nums, k): if notNumsreturnK%=len (Nums) nums.reverse () Self.reverse (Nums,0, K-1) Self.reverse (Nums,k,len (nums)-1) def reverse(self,nums,start,end): whileStart<end:nums[start],nums[end]=nums[end],nums[start] start+=1end-=1
Leetcode 189 Rotate Array