Java one pass 1 ms solution


  • 0
    X
    public void sortColors(int[] nums) {
        if(nums.length==1 || nums==null) return;
        int lasttwo = nums.length-1;
        int firstzero = 0;
        int len=nums.length;
        for(int i=0;i<len;i++){
            if(nums[i]==0) swapTwo(nums,i,firstzero++);
            while(nums[i]==2 && len>i){
                len--;
                swapTwo(nums,i,lasttwo--);
                if(nums[i]==0) swapTwo(nums,i,firstzero++);
            }
        }
    }
    
    private void swapTwo(int[] nums, int i, int j){
        int tmp = nums[i];
        nums[i]=nums[j];
        nums[j]=tmp;
    }

Log in to reply
 

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