0ms, C code for Space O(1)


  • 0
    A

    void sortColors(int* nums, int numsSize) {

    int i, j, temp, red_index, white_index, blue_index;
    bool isredhead= false, iswhitehead= false, isbluehead= false; 
    
    for (i=0; i< numsSize; i++){
        
        if(nums[i]==0){
          if (!isredhead){
              if (iswhitehead){
                temp =nums[i];
                for( j = i; j>white_index; j--){
                nums[j]=nums[j-1];
               }
                nums[white_index] = temp; 
                red_index =white_index;
                white_index++;
                if(isbluehead) blue_index++;
              }else if ( ! iswhitehead && isbluehead){
                temp =nums[i];
                for( j = i; j>blue_index; j--){
                nums[j]=nums[j-1];
               }
                nums[blue_index] = temp; 
                red_index =blue_index;
                blue_index++;
              }
              else{
                red_index =i;
                
              }
              isredhead =true;
          }
          else {
              temp =nums[i];
              for( j = i; j>red_index; j--){
                nums[j]=nums[j-1];
              }
              nums[red_index] = temp;
             if(iswhitehead) white_index++;
             if(isbluehead) blue_index++;
              
          }
        }else if (nums[i]==1){
          if (!iswhitehead ){
              if (isbluehead){
                temp =nums[i];
                for( j = i; j>blue_index; j--){
                nums[j]=nums[j-1];
               }
                nums[blue_index] = temp; 
                white_index =blue_index;
                blue_index++;
              }else{
             white_index =i;
             }
             iswhitehead =true;
          }
          else{
              temp =nums[i];
              for( j = i; j>white_index; j--){
                nums[j]=nums[j-1];
              }
              nums[white_index] = temp;
              if(isbluehead) blue_index++;
          }
        }
        else if (nums[i]==2){
            if (!isbluehead){
             blue_index =i;
             isbluehead =true;
            }else{
                temp =nums[i];
              for( j = i; j>blue_index; j--){
                nums[j]=nums[j-1];
              }
              nums[blue_index] = temp;
            }
        }
       
    }
    

    }


Log in to reply
 

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