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中已经给出了,但是需要遍历两遍,其他的类似方法也需要遍历一遍以上,例如交换元素的方法,第一遍把所有0换到前面,第二遍把所有1接着换到第一遍最后的位置,2自动换到了最后面。那么看看有没有只需要遍历一遍的方法。偶尔看到有这样一种解法,觉得挺巧妙的,但是没有给出太多解释,仔细分析了几遍代码,详细的介绍下:
核心思路就是用三个游标记录最后一个0,1,2的索引,当插入0时,所有索引一次往后移动一个位置(1,2往后复制一个位置),类似的,当插入1时,2往后复制一个位置,插入2时,直接更新2的索引,并进行插入操作。
代码如下:
<span style="font-size:14px;">void sortColors(vector<int>& nums) {
int iLastZero = -1//three indexes...
int iLastOne = -1;
int iLastTwo = -1;
for(size_t i = 0; i < nums.size(); ++i)
{
if (0 == nums[i])//insert 0
{
nums[++iLastTwo] = 2;//index of two backwards a 2
nums[++iLastOne] = 1;
nums[++iLastZero] = 0;
}
else if (1 == nums[i])
{
nums[++iLastTwo] = 2;
nums[++iLastOne] = 1;
}
else if (2 == nums[i])
{
nums[++iLastTwo] = 2;
}
else
{
//for other cases.
}
}
}</span></span>
看一个具体的例子:
给定一个数组:nums: [1,2,0,1,0],以下是每一次遍历后的处理结果。