My Java One-Pass Solutin, easy and concise


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