Question:
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] is rotated to [5,6,7,1,2,3,4].
Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Hint: Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
There are three solutions for this problem:
Solution 1:
We can use temporary array to store k elements.
Time complexity: O(N)
Space complexity: O(k), use extra space
Code:
The solution beat 98% in java submissions.
Solution2:
Reversal, for example:
Time complexity:O(N)
Space complexity:O(1)
Code:
The solution beats 13.19% of java submissions.
Solution3:
Time complexity: O(N)
Space complexity: O(1)
To rotate k steps once for an element. Set all elements to gcd groups.
E.g. nums = [1 2 3 4 5 6], k=2
We use gcd (greatest common divisor) between n and k.
gcd = 2
// count is the number we need swap each path
count = nums.length / gcd - 1 = 2
1st iteration: starts from nums[i=0], keep rotate nums[i+k] until meet the start position
nums = [\_5 2 \_1 4 \_3 6]
2nd iteration: starts from nums[i=1]
nums = [5 \_6 1 \_2 3 \_4]
Code:
References:
http://yucoding.blogspot.com/2015/03/leetcode-question-rotate-array.html
http://www.programcreek.com/2015/03/rotate-array-in-java/
P.s. recommend the website:
http://www.programcreek.com