My O(1) space C solution


  • 2
    B
    void rotate(int nums[], int n, int k) {
        if (n < 2 || k % n==0){
            return ;
        }
        k=k % n;
        
        int indexOfBackup=n-1;
        int i=indexOfBackup;
        int backup=nums[indexOfBackup];
        for(int count=1;count<=n ;count++){
            if(indexOfBackup==(i-k+n)%n){
                nums[i]=backup;
                i--;
                indexOfBackup=i;
                backup=nums[indexOfBackup];  
            }else{
                nums[i]=nums[(i-k+n)%n];
                i=(i-k+n)%n;
            }
        }
    

    }


  • 0
    Y

    What do you mean by this step?

    if(indexOfBackup==(i-k+n)%n){

          nums[i]=backup;
          
          i--;
           
          indexOfBackup=i;
          
          backup=nums[indexOfBackup];  
        }

  • 0
    B

    { '1 ','2 ','3 ','4 ','5 ','6 ','7 ','8 ' } if this is the array ,n=8 ,

    '6#','7#','_','1#','2#','3#','4#','5#' if k=3 ,this "if block" will move the last element(the backup 8) to @3

    '1','_','3','2#','5','4#','7','6#' if k=2 , you put the backup element 8 to @2 ,and backup new element to move the other 4; and so on,,,


Log in to reply
 

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