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.
看到這道題就想到了以前做字符串旋轉是一樣的方法,其中比較好的解就是三步反轉,這樣能比使用將一個一個元素移動的時間複雜度低很多,若是使用上述一個一個移動,那麼對於長度爲n的數組,假設需要移動m個元素,那麼總共需要m*n次操作,同時還需要設立一個變量來保存第一個元素,那麼時間複雜度爲O(mn),空間複雜度爲O(1)。
實現代碼:
public class RotateArray {
public void rotate(int[] nums, int k) {
int m = nums.length;
k %= m;
reverserString(nums, 0, m-k-1);
reverserString(nums, m-k, m-1);
reverserString(nums, 0, m-1);
}
public void reverserString(int[] nums, int n, int m){
while(n < m){
int num = nums[n];
nums[n++] = nums[m];
nums[m--] = num;
}
}
public static void main(String[] args){
int[] nums = {1,2,3,4,5,6,7};
new RotateArray().rotate(nums,3);
for (int num : nums) {
System.out.println("num = " + num);
}
}
上面三次反轉的過程:
這種方法的時間複雜度爲O(n),空間複雜度爲O(1),雖然這道題比較基礎,但是卻能體現了對數組結構的一個理解