Rotate an array of n elements to the right by K steps.
For example, with n = 7 and k = 3, the array is [1,2,3,4,5,6,7]
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.
[Show hint]
Hint:
Could do it in-place with O (1) extra space?
Related Problem:reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
1 Public classSolution {2 Public voidRotateint[] Nums,intk) {3 int[] tmp =New int[K];4 intLen =nums.length;5K%=len;//processing k greater than the array length6 for(inti = 0; I < K; i++){7Tmp[i] = nums[len-k+i];8 }9len--;Ten for(inti = len-k; i>= 0; i--){ Onenums[len--] =Nums[i]; A } - for(inti = 0; I < K; i++){ -Nums[i] =Tmp[i]; the } - } -}
Solution two to the array 0~len-1 inverted once, 0~k-1 reverse, k~len-1 reverse once, you can get the answer:
1 Public classSolution {2 Public voidRotateint[] Nums,intk) {3 intLen =nums.length;4K%=Len;5Reverse (nums,0,len-1);6Reverse (nums,0,k-1);7Reverse (nums,k,len-1);8 }9 Ten Public voidReverseint[] Nums,intSinte) { One while(S <=e) { A intTMP =Nums[s]; -Nums[s] =Nums[e]; -Nums[e] =tmp; thes++; -e--; - } - } +}
189. Rotate Array Java Solutions