Java one pass solution


  • 0
    F
    public void sortColors(int[] nums) {
    	int idx0 = 0;
    	int idx2 = nums.length - 1;
    	int i = 0;
    	while (idx0 <= i && i <= idx2) {
    		if (nums[i] == 0 && idx0 < i) {
    			swap(nums, idx0++, i);
    		} else if (nums[i] == 2 && i < idx2) {
    			swap(nums, idx2--, i);
    		} else
    			i++;
    	}
    }
    
    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.