75. Sort Colors
Given an array withnobjects 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.
S: two pointer O(n)
用left, right 记录首尾,一根行走指针cur,当nums[cur] = 0 交换nums[cur]和nums[left]的值,当nums[cur]=2交换nums[cur]和nums[right]
注意处理cur和left,right重叠的情况,避免死循环
void sortColors(vector<int>& nums) {
if (nums.size() < 2) {
return;
}
int left = 0, right = nums.size() - 1, cur = 0;
while (cur <= right) {
if (nums[cur] == 0 && cur != left) {
swap(nums[left], nums[cur]);
left++;
} else if (nums[cur] == 2 & cur != right) {
swap(nums[cur], nums[right]);
right--;
} else {
cur++;
}
}
}