Accepted Java 1-pass (Dutch national flag problem template)


  • 1
    H
    public void sortColors(int[] nums) {
            if (nums == null || nums.length <= 1) {
                return;
            }
    	int lo = 0, mid = 0, hi = nums.length - 1;
    	while (mid <= hi)
    		switch (nums[mid]) {
                       case 0:
                           swap(nums, lo++, mid++);
    			break;
    		   case 1:
    			mid++;
    			break;
    		   case 2:
    			swap(nums, mid, hi--);
    			break;
    		}
        }
        
        private static void swap(int[] arr, int i, int j){
    		int tmp = arr[i];
    		arr[i] = arr[j];
    		arr[j] = tmp;
    	}
    

Log in to reply
 

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