三色旗问题(数据结构题目)dp

个仅由红、白、蓝这三种颜色的条块组成的条块序列。请编写一个时间

复杂度为O(n)的算法,使得这些条块按蓝、白、红的顺序排好

例如:   R,B,B,W,W,B,R,B,W

排序后:B,B,B,B,W,W,W,R,R

void Three_color_flag(int color[], int n ) //排序为蓝,白,红 
{
int white = 0 ;
int blue = 0 ;
int red = n - 1 ;
while(white <= red)
{
if(color[white] == WHITE) //白色区域为白旗,white++
white ++ ;
else if(color[white] == BLUE ) //白色区域为蓝色,则交换,两边都处理了,各+1
{
swap(color[blue],color[white]);
blue ++;
white ++ ;
}
else
{
while(white < red && color[red] == RED)//为红色则与红色区域交换,红色-1,白色不变,因为换过来的不知道是什么颜色的
red --;
swap(color[red],color[white]);
red -- ;
}
}
}
原文地址:https://www.cnblogs.com/bersaty/p/2368293.html