189. 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.

[show hint]

Hint:
Could you do it in-place with O(1) extra space?

2/21/2017, Java

 1 public class Solution {
 2     public void rotate(int[] nums, int k) {
 3         int rotateSize = k % nums.length;
 4         int[] temp = new int[rotateSize];
 5         int diff = nums.length - rotateSize;
 6 
 7         for(int i = nums.length - rotateSize; i < nums.length; i++) {
 8             temp[i - diff] = nums[i];
 9         }
10 
11         for(int i = diff - 1; i >= 0; i--) {
12             nums[i + rotateSize] = nums[i];
13         }
14 
15         for(int i = 0; i < rotateSize; i++) {
16             nums[i] = temp[i];
17         }
18     }
19 }

别人的算法:三步反转

performance提高并不明显

 1 public class Solution {
 2     public void rotate(int[] nums, int k) {
 3         if ((nums.length == 0) || (k % nums.length == 0)) return;
 4         k %= nums.length;
 5 
 6         reverse(nums, 0, nums.length - 1);
 7         reverse(nums, 0, k - 1);
 8         reverse(nums, k, nums.length - 1);
 9     }
10     private void reverse(int[] nums, int lo, int hi) {
11         int temp;
12         while (lo < hi) {
13             temp = nums[hi];
14             nums[hi] = nums[lo];
15             nums[lo] = temp;
16             lo++;
17             hi--;
18         }
19         return;
20     }    
21 }
原文地址:https://www.cnblogs.com/panini/p/6427190.html