Sort Colors
2016-05-18 15:26
387 查看
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.
思路:可以先统计数组中含有0,1,2的个数。然后重修修改数组的元素即可
class Solution {
public:
void sortColors(vector<int>& nums) {
if(nums.size()<2)
return;
int sortRed=0;
int sortWhite=0;
int sortBlue=0;
for(int i=0;i<nums.size();i++)
{
if(nums[i]==0)
sortRed++;
else if(nums[i]==1)
sortWhite++;
else if(nums[i]==2)
sortBlue++;
}
int i=0;
while(sortRed)
{
nums[i++]=0;
sortRed--;
}
while(sortWhite)
{
nums[i++]=1;
sortWhite--;
}
while(sortBlue)
{
nums[i++]=2;
sortBlue--;
}
}
};
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
思路:可以先统计数组中含有0,1,2的个数。然后重修修改数组的元素即可
class Solution {
public:
void sortColors(vector<int>& nums) {
if(nums.size()<2)
return;
int sortRed=0;
int sortWhite=0;
int sortBlue=0;
for(int i=0;i<nums.size();i++)
{
if(nums[i]==0)
sortRed++;
else if(nums[i]==1)
sortWhite++;
else if(nums[i]==2)
sortBlue++;
}
int i=0;
while(sortRed)
{
nums[i++]=0;
sortRed--;
}
while(sortWhite)
{
nums[i++]=1;
sortWhite--;
}
while(sortBlue)
{
nums[i++]=2;
sortBlue--;
}
}
};
相关文章推荐
- Jquery “回到顶部”
- 解决MindManager缺少mfc100u.dll无法启动的难题-转载
- HDU-3189-Just Do It【分解质因数】
- 转载:VBA中使用vlookup函数
- 浅析C#中StringBuilder类的高效及与String的对比
- 重读java编程思想之复用类之final
- 无密码登陆
- Coursera_机器学习_week7_SVM支持向量机
- python基础深入(元组、字符串、列表、字典)
- 怎么把内存划分为多个ramdisk(别人的经验)
- autotools使用
- JS严格模式下常见问题汇总
- UiAutomator——点击难以识别的控件技巧
- 自定义Dialog
- 《计算机组成与原理》读书笔记1
- time类
- $_SERVER['SCRIPT_FLENAME']与__FILE__
- 存储过程中使用临时表
- 机器学习中使用的神经网络第七讲笔记
- const成员变量与成员函数