Two pass only


  • 0
    K

    Adjust 0's and 1's in place and the 2's are taken care of.

    public void sortColors(int[] nums) {
            int i=0, j = nums.length-1, curr = 0;
            while(curr < 2) {
                while(i<j) {
                    while(i<j && nums[i]==curr) i++; 
                    while(i<j && nums[j]!=curr) j--;
                    swap(nums, i, j);
                }            
                curr++;
                j = nums.length-1;
            }
        }
        
        private void swap(int[] nums, int i, int j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    

Log in to reply
 

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