Just one pass and beats 83.15% java solution and easy to understand


  • 7
    N
    public static void sortColors(int[] nums) {
    	  int m=0,n=0,p=nums.length-1;
    	  while(n<=p)
    	   {
    		   if(0==nums[n]){
    			   int temp=0;
    			   temp=nums[n];
    			   nums[n]=nums[m];
    			   nums[m]=temp;
    			   m++;
    			   n++;
    		   }else if(2==nums[n]){
    			   int temp=0;
    			   temp=nums[p];
    			   nums[p]=nums[n];
    			   nums[n]=temp;
    			   p--;
    		   }else{
    			   n++;
    			   
    		   }
    	   
    	   }
      }

  • 0
    D

    one pass, but switch two nums. better than two passes in some case


Log in to reply
 

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