Sort Colors

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.

Time Complexity
O(N) two passes
Space Complexity
O(1)

思路

Use Count Sort

代码

public void sortColors(int[] nums) {
    //corner case
    if(nums == null || nums.length == 0) return;
    
    //n1 is count of 0, n2 is count of 1, n3 is counto of 2 in the array
    int n1 = 0, n2 = 0, n3 = 0;
    for(int i = 0; i < nums.length; i++){
        if(nums[i] == 0) n1 += 1;
        else if(nums[i] == 1) n2 += 1;
        else if(nums[i] == 2) n3 += 1;
    }
    
    for(int i = 0; i < n1; i++){
        nums[i] = 0;
    }
    for(int i = 0; i < n2; i++){
        nums[n1 + i] = 1;
    }
    for(int i = 0; i < n3; i++){
        nums[n1 + n2 + i] = 2;
    }
}

Follow up

A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

Could you come up with an one-pass algorithm using only constant space?

Time Complexity
O(N) one pass
Space Complexity
O(1)

思路

Use three pointers, i and left start with 0, right start with nums.length - 1. i always move forward.
[0, left] is 0
(left + 1, right) to explore
(right + 1, nums.length - 1) is 2
There are three cases

  1. if nums[i] == 0, swap it with left, then left++, i++.

  2. if nums[i] == 1, i++;

  3. if nums[i] == 2, swap it with right, then right does not move, because the nums[right] is also 2, i++.

代码

public void sortColors(int[] nums) {
    //   0 1 1 0 2 2
    //         i
    //     l   r
    //corner case
    if(nums == null || nums.length <= 1) return;
    int left = 0, right = nums.length - 1;
    int i = 0;
    
    while(i <= right){ //remeber the equal
        if(nums[i] == 0){
            swap(nums, i, left);
            i++;
            left++;
        }else if(nums[i] == 1){
            i++;
        }else if(nums[i] == 2){
            swap(nums, i, right);
            right--;
        }
    }
}
    
    private void swap(int[] nums, int i , int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

annielulu
5 声望5 粉丝