[leetcode] Sort Colors
2015-07-16 21:33
405 查看
From : https://leetcode.com/problems/sort-colors/
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.
Hide Tags
Array Two
Pointers Sort
Hide Similar Problems
(M) Sort List
Solution 1:
统计个数
Solution 2:
双指针
Solution 3:
改进:
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.
Hide Tags
Array Two
Pointers Sort
Hide Similar Problems
(M) Sort List
Solution 1:
统计个数
class Solution { public: void sortColors(vector<int>& nums) { int cnt0=0, cnt1=0, cnt2=0; for(int i=0, len=nums.size(); i<len; i++) { int n = nums[i]; if(n == 0) cnt0++; else if(n == 1) cnt1++; else cnt2++; } for(int i=0; i<cnt0; i++) nums[i] = 0; for(int i=cnt0, n=cnt0+cnt1; i<n; i++) nums[i] = 1; for(int i=cnt0+cnt1, n=cnt0+cnt1+cnt2; i<n; i++) nums[i] = 2; } };
Solution 2:
双指针
class Solution { public: void sortColors(vector<int>& nums) { int n=nums.size(), i0=-1, i2=n, i=0; while(i < i2) { if(nums[i] == 0 && i > i0) { swap(nums[++i0], nums[i]); } else if(nums[i] == 2 && i < i2) { swap(nums[--i2], nums[i]); } else { i++; } } } void swap(int &a, int &b) { int t=a; a = b; b = t; } };
Solution 3:
class Solution { public: void sortColors(vector<int>& nums) { int i=-1, j=-1, k=-1; for(int d = 0, len = nums.size(); d < len; d++) { if(nums[d] == 0) { nums[++k]=2; nums[++j]=1; nums[++i]=0; } else if (nums[d] == 1) { nums[++k]=2; nums[++j]=1; } else if (nums[d] == 2) { nums[++k]=2; } } } };
改进:
class Solution { public: void sortColors(vector<int>& nums) { int i=-1, j=-1; for(int d = 0, len = nums.size(); d < len; d++) { int v = nums[d]; nums[d] = 2; if(v== 0) { nums[++j]=1; nums[++i]=0; } else if (v == 1) { nums[++j]=1; } } } };
相关文章推荐
- IOS--UI--通讯录实战--Plist 取文件
- MySQL 记录的操作
- 获得二叉树中两个节点的所有公共祖先
- Candy
- 程序员对英语的依赖
- pe系统找不到笔记本硬盘怎么办?解决笔记本进入
- 如何获取 Android 设备的CPU核数、时钟频率以及内存大小
- JDBCTemplate---方法介绍和简单示例
- Java并发编程:Callable、Future和FutureTask
- c++ vector push_back 出错或者错误
- Regular Expression Matching
- Java - 初始化
- Python + Selenium 环境搭建
- [Leetcode] Minimum Window Substring
- 蓝桥杯历届试题 带分数
- Redis介绍以及安装
- dp题目遗留暂且记录,以后再回来做
- overflow属性
- 关于JavaScript刷新一次页面的代码块
- Mac新手操作指南(四)