# LeetCode 189: Rotate Array (Java)

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

## 解法一（12%）：

``````public static void rotate(int[] nums, int k) {
if(nums == null || nums.length <= 1)
return;
k = k%nums.length;
int prev = 0;
int next = 0;
int maxComm = maxCommonDivisor(k,nums.length);
for(int i = 0; i < maxComm;i  ){
prev = nums[i];
int j = i k;
j %= nums.length;
while(j != i){
next = nums[j];
nums[j] = prev;
prev = next;
j =k;
j%=nums.length;
}
nums[j] = prev;
}
return;
}
private static int maxCommonDivisor(int m, int n){
while (m % n != 0) {
int temp = m % n;
m = n;
n = temp;
}
return n;
}
``````

## 解法二（12%）：

reverse的函式都是一樣的，所以可以寫一個helper。

``````public static void rotate(int[] nums,int k) {
if(nums == null || nums.length <= 1)
return;
k %=nums.length;
if(k == 0)
return;
helper(nums,0,nums.length-1);
helper(nums,0,k-1);
helper(nums,k,nums.length-1);
}
public static void helper(int[] nums,int start,int end) {
for(int i = start; i <= (end start)/2;i  ) {
int temp = nums[end start-i];
nums[end start-i] = nums[i];
nums[i] = temp;
}
}
``````

``````public void rotate(int[] nums, int k) {
int n = nums.length;
k = k%n;
int[] temp = Arrays.copyOfRange(nums, 0, n-k);
System.arraycopy(nums, n-k, nums, 0, k);
System.arraycopy(temp, 0, nums, k, n-k);
}
``````

Reference： 0ms 5-line java