LeetCode – Sort Colors (Java)

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Java Solution – Counting Sort

We can get the count of each element and project them to the original array.

public void sortColors(int[] nums) {
    if(nums==null||nums.length<2){
        return;
    }
 
    int[] countArray = new int[3];
    for(int i=0; i<nums.length; i++){
        countArray[nums[i]]++;
    }
 
    int j = 0;
    int k = 0;
    while(j<=2){
        if(countArray[j]!=0){
            nums[k++]=j;
            countArray[j] = countArray[j]-1;
        }else{
            j++;
        }
    }
}

3 thoughts on “LeetCode – Sort Colors (Java)”

  1. More simple solution for 1st case (two-pass algorithm):

    public void sortColors(int[] nums) {
    if (nums == null || nums.length < 2)
    return;

    int[] color = new int[3];

    for (int num : nums)
    color[num]++;

    int i = 0;
    for (int j = 0; j 0)
    nums[i++] = j;
    }

    One-pass algorithm:

    public void sortColors(int[] nums) {
    if (nums == null || nums.length < 2)
    return;

    int red = 0;
    int blue = nums.length - 1;
    int i = 0;

    while (i < blue + 1)
    if (nums[i] == 0) {
    nums[i] = nums[red];
    nums[red++] = 0;
    i++;
    }
    else if (nums[i] == 2) {
    nums[i] = nums[blue];
    nums[blue--] = 2;
    }
    else i++;
    }

  2. Another take at solution 2. Sorry it’s in PHP.


    function sortColors(&$inputs) {
    if (!$inputs || count($inputs) $v) {
    for ($j = 0; $j < $v; $j ++) {
    $inputs[$i ++] = $k;
    }
    }
    }

Leave a Comment