79-Sort Colors
来源:互联网 发布:财智软件 倒闭 编辑:程序博客网 时间:2024/06/06 12:34
- Sort Colors
Total Accepted: 99361 Total Submissions: 285131 Difficulty: Medium
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?
题意:对rgb序列排序,相当于对数组排序,只不过元素取值集合为{0,1,2}
用计数排序肯定是可以的,不过需要扫描两遍
但题目要求只能扫描一遍
所以还是有点难度的:
思路:由于只有三种取值,那么只要我们排定了最大和最小的2种元素,剩下的元素就自然在确定的位置了
class Solution {public: void sortColors(vector<int>& nums) { int n=nums.size(); int red=0,blue=n-1; //设定头尾指针,存放0和2 for(int i=0;i<=blue;){//从头至尾扫描 if(nums[i]==2) // 遇到2则放到后面确定位置,同时对i位置新元素进行下一轮 swap(nums[i],nums[blue--]); else if(nums[i]==0)swap(nums[i++],nums[red++]);//遇到0放到前面,检测下一元素 else ++i; //如果不是指定值0或2,不用管,跳到下一元素 } }};
0 0
- 79-Sort Colors
- Sort Colors
- sort colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- leetcode 144. Binary Tree Preorder Traversal-前序遍历|递归|非递归
- Java设计模式(一):单例模式,防止反射和反序列化漏洞
- Android开发项目之一:打招呼
- 数据结构基本概念
- 手机开发实战31——SIM卡软件特性
- 79-Sort Colors
- Windows10 桌面图标设置
- 手机开发实战32——SIM卡文件系统介绍
- 爱康融资无望,重金雇枪手疯狂抹黑美年?
- iOS开发笔记--什么时候调用layoutSubviews
- 手机开发实战33——SIM卡功能
- 5分钟实现Android中更换头像功能
- 数据挖掘常用工具库介绍
- 手机开发实战34——SIM卡应用1