75. Sort Colors
来源:互联网 发布:php信息管理系统 编辑:程序博客网 时间:2024/05/30 04:35
题目
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.
click to show follow up.
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?
思路
本题因为数组数值比较特殊,只有三种0,1,2;那么只要遍历数组,遇到0将其插入数组头部,遇到2将其插入到数组尾部。剩下的1就处在0,2之间。
代码
class Solution {public: void sortColors(vector<int>& nums) { int count =0; for(int i=0;i<nums.size()-count;i++) { if(nums[i]==0&&i!=0) { nums.erase(nums.begin()+i); nums.insert(nums.begin(),0); } else if(nums[i]==2) { count++; nums.erase(nums.begin()+i); nums.insert(nums.end(),2); i--; } } return; }};
- 【sort专题】75. Sort Colors
- 75. Sort Colors
- [LeetCode]75.Sort Colors
- LeetCode --- 75. Sort Colors
- [Leetcode] 75. Sort Colors
- [leetcode] 75.Sort Colors
- 75. Sort Colors
- 【leetcode】75. Sort Colors
- 75. Sort Colors
- [leetcode] 75. Sort Colors
- Leetcode 75. Sort Colors
- *LeetCode 75. Sort Colors
- 75. Sort Colors LeetCode
- 75. Sort Colors
- Leetcode 75. Sort Colors
- 75. Sort Colors
- [LeetCode]75. Sort Colors
- 75. Sort Colors
- 机器学习入门笔记(八)----支持向量机SVM
- ping 丢包或不通时链路测试说明
- 快速排序
- CountDownLatch同步工具类
- leetcode 222. Count Complete Tree Nodes 计算满二叉树的节点数量
- 75. Sort Colors
- 数据库---那些不允许更新的视图
- 高性能CSS
- 嚼得菜根做得大事·《菜根谭》·十一
- java中main函数的参数String[] args 的理解
- 短信验证码 ----- 点击发送并实现定时器
- js中的时间与毫秒数互相转换
- Second week of machine learning on Coursera
- SQL之case when then用法