Questions¶
Difficulty: Easy
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?
Coding¶
Java¶
public class Solution {
public void swap(int[] array, int a, int b) {
int t = array[a];
array[a] = array[b];
array[b] = t;
}
public void reverse(int[] array, int start, int end) {
if (array == null || array.length <= 1) {
return;
}
for (int i = start, j = end; i < j; i++, j--) {
swap(array, i, j);
}
}
public void rotate(int[] nums, int k) {
if (k == 0) {
return;
}
int n = nums.length;
if (k > n) {
k = k % n;
}
reverse(nums, 0, n - 1 - k);
reverse(nums, n - k, n - 1);
reverse(nums, 0, n - 1);
}
}
python¶
# -*- coding: utf-8 -*-
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
if k == 0:
return
n = len(nums)
if k > n:
k = k % n
self.reverse(nums, 0, n - 1 - k)
self.reverse(nums, n - k, n - 1)
self.reverse(nums, 0, n - 1)
def swap(self, array, a, b):
t = array[a]
array[a] = array[b]
array[b] = t
def reverse(self, array, start, end):
if array is None or len(array) <= 1:
return
i, j = start, end
while i < j:
self.swap(array, i, j)
i, j = i + 1, j - 1
if __name__ == "__main__":
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
solution = Solution()
print nums
solution.rotate(nums, 4)
print nums