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.
class Solution {
public:
void sortColors(vector<int>& nums) {
if(nums.empty())
return;
int start = 0;
int current = start;
int end = nums.size()-1;
while(current<=end)
{
if(nums[current] == 0)
{
if(nums[start]!=nums[current])
{
int temp = nums[start];
nums[start] = 0 ;
nums[current] = temp;
}
start++;
current++;
}else if(nums[current] == 1)
{
current++;
}else{
if(nums[current]!=nums[end])
{
int temp = nums[end];
nums[end] = 2;
nums[current] = temp;
}
end --;
}
}
return;
}
};
注:nums[current] == 1时,start++, current++是因为前面已经排好序,nums[current] == 2, end --,后面没有排好序,还需要继续判断。
本文介绍了一种将数组中红、白、蓝三种颜色排序的算法,使用整数0、1、2分别代表红、白、蓝,并通过一次遍历实现原地排序。
956

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



