原题链接在这里:https://leetcode.com/problems/rotate-array/
题目:
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.
题解:
Reverse the whole array[0, n-1], then reverse [0, k-1] and [k, n-1].
Time Complexity: O(n). Space: O(1).
AC Java:
1 public class Solution { 2 public void rotate(int[] nums, int k) { 3 if(nums == null || nums.length == 0){ 4 return; 5 } 6 int len = nums.length; 7 k = k%len; 8 reverse(nums, 0, len-1); 9 reverse(nums, 0, k-1); 10 reverse(nums, k, len-1); 11 } 12 13 private void reverse(int [] nums, int i, int j){ 14 while(i < j){ 15 swap(nums, i++, j--); 16 } 17 } 18 private void swap(int [] nums, int i, int j){ 19 int temp = nums[i]; 20 nums[i] = nums[j]; 21 nums[j] = temp; 22 } 23 }
Method 1 新建一个array res, 找出rotate 后array 和 原来array 的位置对应关系是 res[i] = nums[(i+len-k) % len]. 最后把res 赋值回 nums.
Time Complexity: O(n). Space: O(n).
Method 2 每次只rotate 一个位置,一共循环k次。可以不用额外空间,但也用了更多的时间。
Time Complexity: O(k*n). Space: O(1).
Method 3 先reverse全部array, 在以k为分界点,分别reverse 前半部分[0, k-1], 后半部分[k, len-1]. 三种方法都需要注意k = k%len.
Time Complexity: O(n). Space: O(1).
1 public class Solution { 2 public void rotate(int[] nums, int k) { 3 int len = nums.length; 4 k = k % len; 5 6 /* 7 //Method 1, takes O(n) space, running in O(n) time 8 9 int[] res = new int[len]; 10 11 for(int i = 0;i<len;i++){ 12 res[i] = nums[(i+len-k)%len]; 13 } 14 15 for(int i = 0;i<len;i++){ 16 nums[i] = res[i]; 17 } 18 */ 19 20 /* 21 //Method 2, takes O(k*n) time 22 23 while(k>0){ 24 int temp = nums[len - 1]; 25 for(int i = len-1;i>0;i--) 26 { 27 nums[i] = nums[i-1]; 28 } 29 nums[0] = temp; 30 31 k--; 32 } 33 */ 34 35 //Method 3, reverse the whole array, cut it into two parts, reverse each of them 36 reverse(nums, 0, len-1); 37 reverse(nums, 0, k-1); 38 reverse(nums, k, len-1); 39 } 40 41 private void reverse(int[] arr, int left, int right){ 42 while(left<right){ 43 int temp = arr[left]; 44 arr[left] = arr[right]; 45 arr[right] = temp; 46 left++; 47 right--; 48 } 49 } 50 }