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?
这道题的难点在于只能遍历一遍!
方法是使用游标。
class Solution {
public:
void sortColors(int A[], int n) {
int a = -1;
int b = -1;
int c = -1;
for (int i=0; i<n; i++)
{
if (A[i] == 0)
{
A[++c] = 2;
A[++b] = 1;
A[++a] = 0;
}
else if (A[i] == 1)
{
A[++c] = 2;
A[++b] = 1;
}
else if (A[i] == 2)
{
A[++c] = 2;
}
}
}
};
本文介绍了一种一过性排序算法,该算法用于对包含红色、白色和蓝色三种颜色的对象数组进行排序,使得相同颜色的对象相邻,并按红、白、蓝的顺序排列。通过使用三个指针a、b、c来跟踪不同颜色元素的位置,该算法能在一次遍历内完成排序,且仅使用常数级别的额外空间。
1401

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



