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] .
Hint:
Could do it in-place with O (1) extra space?
link:https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/646/
Solution 1:
The first thing to think about is to open an array, iterate through the array nums as required, and put it in a new array.
For example: [1,2,3,4,5,6] n=6 k=2 divide the array into two parts [1,2,3,4,5,6] respectively into the new array to be able to
Code implementation:
Public void rotate (intint k) { intnewint[ Nums.length]; for (int i = 0; i < nums.length; i++) { + k)% nums.length] = nums[i]; } for (int i = 0; i < nums.length; i++) { = a[i]; } }
Solution 2:
Here's a neat way to do it:
The array is divided into two halves using the length-k of the array;
Reverse the left and right arrays;
Reverse Total Group
To give an example:
1 2 3 4 5 6 7 If k = 3, it becomes 5 6 7 1 2 3 4
1 2 3 4 5 6 7 middle = 7-3 = 4, divided into 4 digits to the left, 3 digits to the right
4 3 2 1 7 6 5 reverse the left and right, respectively.
5 6 7 1 2 3 4 reverse the Totals group and you get the answer.
Public classSolution { Public voidRotateint[] Nums,intk) {if(Nums = =NULL|| Nums.length = = 0 | | K% Nums.length = = 0) return; intturns = k%nums.length; intMiddle = nums.length-turns; Reverse (Nums,0, middle-1);//Reverse Left partReverse (nums, middle, nums.length-1);//Reverse Right partReverse (nums, 0, nums.length-1);//Reverse Whole part } Public voidReverseint[] arr,intSinte) { while(S <e) {inttemp =Arr[s]; Arr[s]=Arr[e]; Arr[e]=temp; S++; E--; } }}
Leetcode-rotate Array Rotation