One-pass using instance constant space java solution


  • 0
    L
    public void sortColors(int[] nums) {
            int len = nums.length,index=0,index0=0,index2=len-1;
            while(index<=index2){
                if(nums[index] == 1){
                    index++;
                }else if(nums[index] == 0){
        			nums[index] = 1;
        			nums[index0]=0;
            		index0++;
            		index++;
            	}else if(nums[index] == 2){
            		while(index2>=0 && nums[index2] == 2 && index<=index2){
            			index2--;
            		}
            		if(index>index2){
            		    break;
            		}
            		nums[index] = 1;
            		if(nums[index2]==0){
            		    nums[index0]=0;
            	        index0++;
            		}
            		nums[index2] = 2;
            		index2--;
            		index++;
            	}
            }
        }

Log in to reply
 

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