My Java solution


  • 0
    Z
    public class Solution {
    public void rotate(int[] nums, int k) {
        if(k<=0){
            return ; 
        }
        if(k==nums.length) return ;
        else{
            if(k>nums.length) k=k-nums.length;
            int [] a = new int[k];
            for(int i=nums.length-k,j=0;i<nums.length;i++,j++)
                    a[j]=nums[i];
            for(int j=0;j<nums.length;j++){
            if(j<nums.length-k)
                nums[nums.length-j-1]=nums[nums.length-j-1-k];
            else
                nums[nums.length-j-1] = a[nums.length-j-1];
        }
       }
    }
    

    }


  • 3
    P

    I think if you usek=k%nums.lengthrather than k=k-nums.length, it will be better. Because k might be over several times comparing to length.``


  • 0
    Z

    yeap, your point is more superb~


Log in to reply
 

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