Problem
Analysis Process
The question is known as the Dutch National Flag problem
We use three Pointers (p0, p2, and curr) to track the right-most boundary of 0, the left-most boundary of 2, and the currently considered element, respectively
The idea of this solution is to move the curr pointer along the array, if nums[curr] = 0, then it is interchanged with nums [p0]; If nums [curr] = 2, it is interchanged with nums [p2]
Code
golang
func sortColors(nums []int) {
if len(nums)==0{
return
}
// Initializes three Pointers
p0:=0
p2:=len(nums)-1
curr:=0
// curr traverse
for curr<=p2{
if nums[curr]==0{ // Swap the p0 and curr elements
nums[curr]=nums[p0]
nums[p0]=0
p0++
}else if nums[curr]==1{
curr++
}else if nums[curr]==2{ //Swap the k and curr elements
nums[curr]=nums[p2]
nums[p2]=2
p2--
}
if curr<p0{
curr=p0
}
}
}
java
class Solution {
public void sortColors(int[] nums) {
// for all idx < i : nums[idx < i] = 0
// j is the subscript of the element under consideration
int p0 = 0, curr = 0;
// for all idx > k : nums[idx > k] = 2
int p2 = nums.length - 1;
int tmp;
while (curr <= p2) {
if (nums[curr] == 0) {
// Swap the p0 and curr elements
// i++,j++
tmp = nums[p0];
nums[p0++] = nums[curr];
nums[curr++] = tmp;
}
else if (nums[curr] == 2) {
// Swap the k and curr elements
// p2--
tmp = nums[curr];
nums[curr] = nums[p2];
nums[p2--] = tmp;
}
else curr++;
}
}
}