# My accepted solution in java. An easy solution by doubling the array.

• public class Solution {

``````public void rotate(int[] nums, int k) {
int length=nums.length;
int rk=k%length;
int [] copy=new int[length*2];
for(int i=0;i<2*length;i++){
copy[i]=nums[i%length];
}
for(int t=length-rk,i=0;t<2*length-rk;t++,i++)
{
nums[i]=copy[t];

}

}
``````

}

• Why need an array of double-length? See code below.

``````public void rotate(int[] nums, int k) {
int len=nums.length;
int[] nums_cp=new int[len];

for(int i=0; i<len; i++){
nums_cp[(i+k)%len]=nums[i];
}

//NOT WORK, reference can not be modified!!!
//nums=nums_cp;

//SO, we copy nums_cp to nums
for(int i=0; i<len; i++){
nums[i]=nums_cp[i];
}

}``````

• if you tend to use O(n) extra memory, just use exactly int[n] is enough.

• @hzucd i came up with the same solution. But on submitting the answer, I am getting time exceeded error. Could you share how you resolved it?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.