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
Title tag: Array
The topic gives us an array and a K. Let's rotate the array k times.
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 Totals 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 total group and you'll get the answer .
Java Solution:
Runtime beats 15.37%
Completion Date: 04/13/2017
Keywords: Array
Key points: using K to divide the array into two halves; reverse array of the left and right sides; Reverse Total Group
1 Public classSolution2 {3 Public voidRotateint[] Nums,intk)4 {5 if(Nums = =NULL|| Nums.length = = 0 | | K% Nums.length = = 0)6 return;7 8 intturns = k%nums.length;9 intMiddle = nums.length-turns;Ten OneReverse (nums, 0, middle-1);//Reverse Left part AReverse (nums, middle, nums.length-1);//Reverse Right part -Reverse (nums, 0, nums.length-1);//Reverse Whole part - } the - Public voidReverseint[] arr,intSinte) - { - while(S <e) + { - inttemp =Arr[s]; +Arr[s] =Arr[e]; AArr[e] =temp; at -s++; -e--; - } - } -}
Resources:
Http://www.cnblogs.com/grandyang/p/4298711.html
Leetcode algorithm Topic List-Leetcode algorithms Questions list
Leetcode 189. Rotate Array (rotated array)