我们有三种不同类型的N球:红色(r),蓝色(b)和白色(w)。
我需要对它们进行排序,以便红球出现第一,然后是所有白球,最后是所有蓝球。
示例:
在:bwrwrbbrwwrb
string[] arrBalls = { "b", "w", "r", "w", "r", "b", "b", "r", "w", "w", "r", "b" };
输出:rrrrwwwwbbbb
我需要找到线性O(n)算法。
更新: C#代码
string[] arrBalls = { "b", "w", "r", "w", "r", "b", "b", "r", "w", "w", "r", "b" };
int index_red = 0;
int index_blue = arrBalls.Length - 1;
for (int i = 0; i < arrBalls.Length; i++)
{
if (arrBalls[i] == "r" && index_red != i)
{
string TempRed = arrBalls[index_red];
arrBalls[index_red] = arrBalls[i];
arrBalls[i] = TempRed;
if (arrBalls[index_red] == "r")
{
while(arrBalls[index_red] == "r")index_red++;
}
else
{
index_red++;
}
}
if (arrBalls[i] == "b" && index_blue != i)
{
string TempRed = arrBalls[index_blue];
arrBalls[index_blue] = arrBalls[i];
arrBalls[i] = TempRed;
if (arrBalls[index_blue] == "b")
{
while (arrBalls[index_blue] == "b") index_blue--;
}
else
{
index_blue--;
}
}
}
答案 0 :(得分:5)
将三种类型的球中的每一种计算为3个变量。我们假设您计算了R
个红球,B
个蓝色球和W
个红色球。然后输出R "r"
,然后输出W "w"
,然后输出B "b"
。