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.
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?
这题很没意思, 本来以为说是把把相同颜色的放在一起就行了 比如说 [1,0]就是满足要求的,但实际上题目是还要排序,排序成形如
[0,0,0……,1,1,1……2,2,2……]的排过序的, 那就一个选择排序最简单了 题目说不能用库函数的排序。
class Solution {
public:
void sortColors(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
for (int i = 0; i < n - 1; ++i)
{
for (int j = i + 1; j < n; ++j)
{
int temp = 0;
if (A[i] > A[j])
{
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
}
}
};
另外这里给一个非排序的算法,将相同颜色的放到相邻的位置
//class Solution {
//public:
// void sortColors(int A[], int n) {
// // Note: The Solution object is instantiated only once and is reused by each test case.
// for (int i = 0, temp = -1; i < n - 2; ++i)
// {
// for (int j = i + 1; j < n - 1; ++j)
// {
// if (A[i] == A[j + 1] && A[j] != A[j + 1])
// {
// temp = A[i + 1];
// A[i + 1] = A[j + 1];
// A[j + 1] = temp;
// break;
// }
// if (A[i] == A[j])
// break;
// }
// }
// }
//};