# leetcode刷题，总结，记录，备忘 75

183人阅读 评论(0)

leetcode75

### Sort Colors

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.

class Solution {
public:
void sortColors(vector<int>& nums) {
vector<int> temp;
vector<int>::iterator it = nums.begin();
while ((it = find(it, nums.end(), 0)) != nums.end())
{
temp.push_back(*it);
it++;
}
it = nums.begin();
while ((it = find(it, nums.end(), 1)) != nums.end())
{
temp.push_back(*it);
it++;
}
it = nums.begin();
while ((it = find(it, nums.end(), 2)) != nums.end())
{
temp.push_back(*it);
it++;
}
nums = temp;
}
};

class Solution {
public:
void sortColors(vector<int>& nums) {
if (nums.size() <= 1)
return;
int s = -1, e = nums.size();
int it = 0, temp;
while (it < nums.size())
{
if (nums[it] == 0)
{
if (it > s)
{
temp = nums[it];
nums[it] = nums[++s];
nums[s] = temp;
}
else it++;
}else if  (nums[it] == 2)
{
if (it < e)
{
temp = nums[it];
nums[it] = nums[--e];
nums[e] = temp;
}
else
it++;
}
else
it++;
}

}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：29136次
• 积分：747
• 等级：
• 排名：千里之外
• 原创：131篇
• 转载：2篇
• 译文：0篇
• 评论：6条
文章分类
阅读排行
最新评论