# My accepted java solution, O(n) time and O(1) space. But it takes 200ms, why? How to improve it?

• This is my java solution. It only loop the array once and takes O(1)space. But it takes 200ms to execute. I found that most java solution is around 100ms. Why this happened? Any suggestion is appreciated.

``````public class Solution {
public void rotate(int[] nums, int k) {
int temp=nums[0],temp2=0;
int cur=0,orig=0,target=0;  //cur is the pointer points to the current element, target is the target location
//after moving k steps. orig is to memorize the start point. If the target is
// equal to origin, it means the visited elements forms a circle. Then we
//increase the cur and orig by 1.
int n=0;                           // n is the counter of steps, we need nums.length() steps to rotate the array.
if(nums.length>1){
while(n<nums.length){
target=(cur+k)%nums.length;
temp2=nums[target];
nums[target]=temp;
temp=temp2;
n++;
if(target==orig&&cur+k>=nums.length){
orig=orig+1;
cur=orig;
if(cur<nums.length)
temp=nums[cur];
}else{
cur=target;
}
}
}
}
``````

}

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