【LeetCode从零单刷】Sort Colors
2015-09-21 19:38
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.
Note:
You are not suppose to use the library's sort function for this problem.
解答:
说是全局排序,但其实同一种颜色内部,根本无所谓顺序都是相同的。所以,所需要知道的只是每种颜色最开始出现的位置。
但是这道题并没有结束,还有更多的要求:
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?
当只能遍历一次数组的时候呢?有两个思路:
类似快排思想,设置两个游标:start 和 end,比1小的放到 start 位置,比1大的放到 end 位置,然后逐渐往中间靠拢;
设置三个游标,分别标记0,1,2的开始位置。与以上方法不同的是,边移动边赋值,这样会导致一个问题:新老值的赋值顺序
这里有篇博客贴出了代码:http://www.cnblogs.com/ganganloveu/p/3703746.html
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) { int len = nums.size(); int a = 0, b = 0, c = 0; for(int i=0; i<len; i++) { if(nums[i] == 0) a++; if(nums[i] == 1) b++; if(nums[i] == 2) c++; } nums.clear(); for(int i=0; i<len; i++) { if(i < a) nums.push_back(0); else if(i < (a+b)) nums.push_back(1); else nums.push_back(2); } } };
但是这道题并没有结束,还有更多的要求:
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?
当只能遍历一次数组的时候呢?有两个思路:
类似快排思想,设置两个游标:start 和 end,比1小的放到 start 位置,比1大的放到 end 位置,然后逐渐往中间靠拢;
设置三个游标,分别标记0,1,2的开始位置。与以上方法不同的是,边移动边赋值,这样会导致一个问题:新老值的赋值顺序
这里有篇博客贴出了代码:http://www.cnblogs.com/ganganloveu/p/3703746.html
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性
- C++ Custom Control控件向父窗体发送对应的消息