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.
Solutions
1. Counting Sort. Time complexity O(3*N)
public class Solution {
public void sortColors(int[] nums) {
if(nums == null || nums.length == 0){
return;
}
int[] rwy = new int[3];
for(int i = 0; i < nums.length; i++){
rwy[nums[i]]++;
}
for(int i = 1; i < rwy.length; i++){
rwy[i] += rwy[i - 1];
}
int[] sortedArray = new int[nums.length];
for(int i = 0; i < nums.length; i++){
rwy[nums[i]]--;
sortedArray[rwy[nums[i]]] = nums[i];
}
System.arraycopy(sortedArray, 0, nums, 0, nums.length);
}
}
2. One pass, two pointers. Time complexity O(N)
public class Solution {
public void sortColors(int[] nums) {
if(nums == null || nums.length == 0){
return;
}
int ind0 = 0; // index of last 0
int ind1 = 0; // index of last 1
for(int i = 0; i < nums.length; i++){
if(nums[i] == 0){
nums[i] = 2;
nums[ind1++] = 1;
nums[ind0++] = 0;
}else if(nums[i] == 1){
nums[i] = 2;
nums[ind1++] = 1;
}
}
}
}