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.
// I didn't pass this question for several tests.
// It needs three pointers. One for 0, one for 1, one for 2.
/ red 0, white 1, blue 2
#include <vector>
#include <iostream>
using namespace std;
void sortColors(vector<int>& nums) {
if(nums.size() <= 1) return;
int i = 0; // pointer for 0
int k = nums.size() - 1; // pointer for 2
int j = nums.size() - 1; // pointer for 1
while(i <= j) {
if(nums[i] == 0) {
i++;
} else if(nums[i] == 2) {
swap(nums[i], nums[k--]); // i is not increasing.
if(k < j) j = k; // update the 1's pointer.
} else {
swap(nums[i], nums[j--]); // i is not increasing.
}
}
}
int main(void) {
vector<int> nums{0, 2, 1, 0, 2, 2};
sortColors(nums);
for(int i = 0; i < nums.size(); ++i) {
cout << nums[i] << endl;
}
cout << endl;
}
Sort K colors.
Two Method: 1: using quickselect, it takes NK time. 2: bucket sort, time complexity O(1). Bucket sort

本文介绍了一种不使用标准库排序函数解决红白蓝三色排序问题的方法。通过三个指针分别跟踪红色(0)、白色(1)和蓝色(2),实现了相同颜色相邻且按红白蓝顺序排列的目标。
3115

被折叠的 条评论
为什么被折叠?



