Optimal: Dutch national flag
Time O(n) Space O(1)low = 0, mid = 0, high = n − 1. If nums[mid] is 0, swap with low and advance both; if 1, advance mid; if 2, swap with high and decrease high (don't advance mid: the swapped-in value is unchecked).
nums = [2, 0, 2, 1, 1, 0]Step 1/4nums[mid] = 2: swap with hi; hi−−.
class Solution {
public void sortColors(int[] nums) {
int low = 0, mid = 0, high = nums.length - 1;
while (mid <= high) {
if (nums[mid] == 0) swap(nums, low++, mid++);
else if (nums[mid] == 1) mid++;
else swap(nums, mid, high--);
}
}
private void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }
}Verdict: One pass.