Simplest java solution with clear explanation < 1ms


  • 0
    public void sortColors(int[] nums) {
        if (nums == null || nums.length == 0)
            return;
    
        int i = 0, j = 0, k = nums.length - 1;
        while (j <= k) {
            if (nums[j] == 0) {
                swap(nums, i, j);
                i++;
                j++;
            } else if (nums[j] == 1) {
                j++;
            } else if (nums[j] == 2) {
                swap(nums, k, j);
                // Notice that j is NOT incremented deliberately since you don't
                // got swapped in its place from the "original" k index. All we
                // can say with certainty is that the "new" k has value 2,
                // but not much more than that.
                k--;
            }
        }
    }
    
    private 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.