Why is it not working?


  • 0
    M

    void rotate(int nums[], int n, int k) {
    int copy[n];
    for (int i = 0; i < n; i++) {
    int newIndex;
    if ((i + k) > (n-1)) {
    newIndex = i + k - n;
    } else {
    newIndex = i + k;
    }
    copy[newIndex] = nums[i];
    }
    nums=copy;
    }


  • 0
    D

    when you copy a value to another destination, the value in that location is replaced.
    You should temporarily store somewhere.

    try this :

    void rotate(int nums[], int n, int k) 
     {
    
     int i=0,j,temp;
     for(j=1;j<=k;++j)
        {
         temp=nums[n-1];
         for(i=n-1;i>0;--i)
                nums[i]=nums[i-1];
         nums[0]=temp;
        }
    }

  • 0
    C

    name of array is actually is the reference to the value, using "=" operation is copying the reference, not value.


Log in to reply
 

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