###### Rotate Array

Problem

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]. How many different ways do you know to solve this problem?

1.复制数组，最简单的方式。
2.采用类似冒泡排序的方式，每次将最右边一个移到最前面。
3.采用旋转逆序的方式。

talk is cheap,show me the code!

public class RotateArray {

public static void printArray(int[] array) {
for(int i=0; i<array.length; i++) {
System.out.print(array[i] + " ");
}
}

//方法一:复制数组,时间复杂度与空间复杂度均为O(n)
public static void rotate(int[] nums, int k) {
if(k > nums.length) {
k%= nums.length;
}

int[] result = new int[nums.length];

for(int i=0; i<k; i++) {
result[i] = nums[nums.length-k+i];
}

int j = 0;
for(int i=k; i<nums.length; i++) {
result[i] = nums[j];
j++;
}

System.arraycopy(result,0,nums,0,nums.length);
}

//方法二:类似于冒泡排序,时间复杂度O(nk),空间复杂度O(1)
public static void bubble_rotate(int[] nums, int k) {
if(nums == null || k < 0) {
throw new IllegalArgumentException("Illegal argument!");
}

for(int i=0; i<k; i++) {
for(int j=nums.length-1; j>0; j--) {
int tmp = nums[j];
nums[j] = nums[j-1];
nums[j-1] = tmp;
}
}
}

//方法三:逆序的方式,时间复杂度O(n),空间复杂度O(1)
public static void reverse_rotate(int[] nums, int k) {
if(nums == null || k < 0) {
throw new IllegalArgumentException("Illegal argument!");
}

reverse_array(nums,0,k-1);
reverse_array(nums,k,nums.length-1);
reverse_array(nums,0,nums.length-1);
}

public static void reverse_array(int[] array, int left, int right) {
if (array == null || array.length == 0 || left < 0 || right < 0) {
throw new IllegalArgumentException("Illegal argument!");
}

while(left < right) {
int tmp = array[left];
array[left] = array[right];
array[right] = tmp;
left++;
right--;
}
}

public static void main(String[] args) {
int[] nums = {1,2,3,4,5,6,7};
reverse_rotate(nums,3);
printArray(nums);
}
}


#### 189. Rotate Array [easy] (Python)

2016-07-28 10:32:27

#### LeetCode189——Rotate Array两种解法（一种易读，一种高效）

2015-02-26 09:54:19

#### Leetcode 189: Rotate Array

2015-03-06 07:51:14

#### Rotate Array数组旋转

2016-08-17 21:37:05

#### Leetcode：189. Rotate Array（JAVA）

2016-03-21 16:31:54

#### LeetCode(189) Rotate Array

2015-03-20 12:24:02

#### Rotate Array--Leetcode(Java)

2015-02-26 20:41:12

#### 【LeetCode-面试算法经典-Java实现】【189-Rotate Array（旋转数组）】

2015-08-24 07:13:21

#### 【LeetCode】Rotate Array 旋转数组

2015-04-23 15:38:43

#### LeetCode 189 Rotate Array（旋转数组）

2016-01-28 15:10:38

Rotate Array