Not sure why it's wrong, pls help.


  • 0
    7
    public void rotate(int[] nums, int k) {
        int len = nums.length;
        
        if(len<2||len==k){
            return;
        }
        
        if(k>len){
            k=k%len;
        }
        int[] copy = new int[len];
        for(int i=0;i<k;i++){
            copy[i] = nums[len-k+i];
        }
        
        for(int j=0;j<len-k;j++){
            copy[k+j] = nums[j];
        }
        nums = copy;
    }
    

    I tested in my local for input: [1,2], 1 and it gives the [2,1]

    But when tested here, I found the error is always :
    Input: [1,2], 1
    Output: [1,2]
    Expected: [2,1]

    I'm a little bit conused, pls help.


  • 3

    You're not modifying the original array. No, nums = copy; doesn't copy the data, it only changes your local pointer from original to copy. Which is worthless.


  • 0
    7

    Thanks a lot! This is the problem. I have no choice but use another loop to copy.


Log in to reply
 

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