75. Sort Colors

use bucket sort

T: O(n)

S: O(1)

class Solution {
    public void sortColors(int[] nums) {
        int[] bucket = new int[3];
        for (int num : nums) {
            bucket[num]++;
        }
        int idx = 0;
        for (int i = 0; i < nums.length; i++) {
            while (idx < 3 && bucket[idx] == 0) {
                idx++;
            }
            nums[i] = idx;
            bucket[idx]--;
        }
    }
}

use pivot partition, run 2 times partition

time: O(n)

space: O(1)

class Solution {
    public void sortColors(int[] nums) {
        // write your code here
        
        // put 0 on 1's left
        int start = partition(nums, 0, 1);
        
        // then put 1 on 2 left (begin with 0's end)
        partition(nums, start, 2);
    }

    private int partition(int[] nums, int start, int pivot) {

        int left = start;
        int right = nums.length - 1;

        while (left <= right) {
            while (left <= right && nums[left] < pivot) {
                left++;
            }
            while (left <= right && nums[right] >= pivot) { // equal, 所以最後 left, right 相交, 中間沒東西
                right--;
            }
            if (left <= right) {
                swap(nums, left, right);
                left++;
                right--;
            }
        }
        return left;
    }
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

The problem is known as Dutch National Flag Problem and first was proposed by Edsger W. Dijkstra. The idea is to attribute a color to each number and then arrange them following the order of colors on the Dutch flag.

T: O(n)

S: O(1)

class Solution {
    public void sortColors(int[] nums) {
        int p0 = 0;
        int cur = 0;
        int p2 = nums.length-1;

        while (cur <= p2) {
            if (nums[cur] == 0) {
                int temp = nums[p0];
                nums[p0++] = nums[cur];
                nums[cur++] = temp;
            } else if (nums[cur] == 2) {
                int temp = nums[p2];
                nums[p2--] = nums[cur];
                nums[cur] = temp;
            } else {
                cur++;
            }
        }
    }
}

Last updated

Was this helpful?