My java solution with explanation


  • 1
    B

    so the idea is that from [0, i) are all 0's, [i, j) are all 1's, [k, nums.length) are all 3's, and from [j, k) are unsorted numbers.

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