Question
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] .
Solution 1 Bubble Rotate
Similar with bubble sort, time complexity O (k * n), Space cost O (1)
1 Public classSolution {2 Public voidRotateint[] Nums,intk) {3 intLength =nums.length;4 if(k >=length)5K = k%length;6 if(k = = 0)7 return;8 for(inti = 0; I < K; i++) {9 for(intj = length-1; J > 0; j--) {Ten intTMP =Nums[j]; OneNUMS[J] = nums[j-1]; ANUMS[J-1] =tmp; - } - } the } -}Solution 2 Traverse
Key to this solution are to make a copy of original array. Time complexity O (n), Space cost O (n).
Solution 3 Reversal
Assuming we are given {1,2,3,4,5,6} and order 2. The basic idea is:
1. Divide the array, parts:1,2,3,4 and 5, 6
2. Rotate First part:4,3,2,1,5,6
3. Rotate Second part:4,3,2,1,6,5
4. Rotate the whole array:5,6,1,2,3,4
Time complexity O (n), Space cost O (n)
1 Public classSolution {2 Public voidRotateint[] Nums,intk) {3 intLength =nums.length;4 if(k >=length)5K = k%length;6 if(k = = 0)7 return;8Reverse (nums, 0, length-k-1);9Reverse (nums, length-k, length-1);TenReverse (nums, 0, Length-1); One } A Private voidReverseint[] Nums,intStartintend) { - if(start = = End | | nums.length = = 1) - return; the while(Start <end) { - intTMP =Nums[start]; -Nums[start] =Nums[end]; -Nums[end] =tmp; +start++; -end--; + } A } at}
Rotate Array Solution