lintcode刷题——颜色分类
来源:互联网 发布:网络推广好处 编辑:程序博客网 时间:2024/05/17 06:43
原题如下:
颜色分类
给定一个包含红,白,蓝且长度为 n 的数组,将数组元素进行分类使相同颜色的元素相邻,并按照红、白、蓝的顺序进行排序。
我们可以使用整数 0,1 和 2 分别代表红,白,蓝。
注意事项
不能使用代码库中的排序函数来解决这个问题。
排序需要在原数组中进行。
给你数组 [1, 0, 1, 2]
, 需要将该数组原地排序为 [0, 1, 1, 2]
。
1、只有三个数字0,1,2,所以只需要考虑把0全部放在左边,把2全部放在右边即可;
2、用两根指针,用类似快速排序的算法来做,如果当前的数是0,且下标不为左边的指针所指的位置,交换,同理,如果当前的值为2,下标不为右边的指针所指的位置,交换,否则,继续向前搜索。
具体的C++代码如下:
class Solution{
public:
/**
* @param nums: A list of integer which is 0, 1 or 2
* @return: nothing
*/
void sortColors(vector<int> &nums) {
// write your code here
int l=0;
int r=nums.size()-1;
int len=nums.size();
for(int i=0;i<min(len,r+1);)
{
if(nums[i]==0)
{
if(i==l)
{
i++;
}
else
{
swap(nums[i],nums[l]);
l++;
}
}
else if(nums[i]==2)
{
swap(nums[i],nums[r]);
r--;
}
else
{
i++;
}
}
}
};
- lintcode刷题——颜色分类
- LintCode-颜色分类
- lintcode-颜色分类-148
- Lintcode: 颜色分类
- 【Lintcode】颜色分类
- LintCode:颜色分类
- lintcode--颜色分类
- 颜色分类-LintCode
- [LintCode] 颜色分类 Sort Colors
- [Lintcode]Sort Colors颜色分类
- 排颜色问题——数组 leetcode lintcode
- 算法爱好者——颜色分类 ? 待解决
- 颜色分类
- 颜色分类
- 颜色分类
- 颜色分类
- 颜色分类
- 颜色分类
- HBase Shell命令
- frament的生命周期和返回栈
- 73
- 二叉树的删除策略
- Android 开源1:获取并解析网页信息(Jsoup)
- lintcode刷题——颜色分类
- Android SharedPreferences
- DNS服务器地址小总结
- DOM、SAX、PULL解析
- Entity Framework入门
- PHP路径指定web路径的方法
- 贺卡应用
- BZOJ 1176: [Balkan2007]Mokia CDQ
- CentOS7 编译安装snmpd,解决与与Mariadb10冲突问题