Question
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.
Note:
You are not suppose to use the library's sort function for this problem.
Solution 1 -- Counting Sort
Straight way, time complexity O(n), space cost O(1)
public class Solution {
public void sortColors(int[] nums) {
int[] count = new int[3];
int length = nums.length;
for (int i = 0; i < length; i++)
count[nums[i]]++;
for (int i = 0; i < count[0]; i++)
nums[i] = 0;
for (int i = 0; i < count[1]; i++)
nums[i + count[0]] = 1;
for (int i = 0; i < count[2]; i++)
nums[i + count[0] + count[1]] = 2;
}
}
Solution 2 -- Two Pointers
We can use two pointers here to represent current red position and blue position. redIndex starts from 0, and blueIndex starts from length - 1.
We traverse once from 0 to blueIndex.
Each time we find nums[i] is not 1:
if nums[i] is 0, we move it to redIndex position
if nums[i] is 2, we move it to blueIndex position
Time complexity O(n), space cost O(1)
public class Solution {
public void sortColors(int[] nums) {
int length = nums.length;
int redIndex = 0, blueIndex = length - 1, i = 0;
while (i <= blueIndex) {
// If current color is red, we need to switch it to red position
if (nums[i] == 0) {
// Switch nums[i] with nums[redIndex]
nums[i] = nums[redIndex];
nums[redIndex] = 0;
redIndex++;
i++;
} else if (nums[i] == 2) {
// If current color is blue, we need to switch it to blue position and check switched color
// Switch nums[i] with nums[blueIndex]
nums[i] = nums[blueIndex];
nums[blueIndex] = 2;
blueIndex--;
} else {
i++;
}
}
}
}