Why is my code wrong? Any help would be appreciated


  • 0
    S
    public class Solution {
    public void rotate(int[] nums, int k) {
        int [] newArray = new int[nums.length];
        int pivot= nums.length - k ;
        int i=0;
        while(pivot < nums.length && i < nums.length){
            newArray[i]=nums[pivot];
            i++;
            pivot++;
             }
        while(i<=nums.length){
             newArray[i]=nums[i];
        }
    

    }
    }


  • 0
    C

    if k > nums.length then it will be wrong.
    k = k%nums.length;


  • 0
    P

    your 2nd while loop has a mistake.

    Instead of:

    while(i<=nums.length){
    newArray[i]=nums[i];
    }

    It should be:
    int j=0;
    while(i<=nums.length){
    newArray[i]=nums[j++];
    }


  • 0
    P

    you should also copy your entire newArray into nums array. As the function's return type is void, we can't return newArray.


Log in to reply
 

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