leetcode_75. Sort Colors题解
来源:互联网 发布:淘宝店铺音乐要钱吗 编辑:程序博客网 时间:2024/06/07 07:31
题目链接
【题目】
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.
【分析】
将数组中的数按颜色排序,其实就是按0,1,2排序
解法1:
用count计算0,1,2的个数,然后从0到2开始往后排
class Solution {public: void sortColors(vector<int>& nums) { int count[3] = {0}; for( int i = 0 ; i < nums.size() ; i ++ ){ count[nums[i]] ++; } for( int i = 0 , index = 0 ; i < 3 ; i ++ ){ for( int j = 0 ; j < count[i] ; j ++ ) nums[index++] = i; } }};
解法2:
class Solution {public: void sortColors(vector<int>& nums) { int red = 0 ; int blue = nums.size() - 1; for( int i = 0 ; i < blue + 1 ; ){ if( nums[i] == 0 ) swap( nums[i++] , nums[red++] ); else if( nums[i] == 2 ) swap( nums[i] , nums[blue--] ); else i++; } }};
0 0
- leetcode_75. Sort Colors题解
- leetcode_75. Sort Colors
- LeetCode题解:Sort Colors
- [题解][LeetCode][Sort Colors]
- Lintcode143 Sort Colors || solution 题解
- Lintcode148 Sort Colors solution 题解
- LeetCode 题解(5):Sort Colors
- Sort Colors
- sort colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- 甲骨文/夾骨學: 炎皇
- vuex2.0小demo
- 编译内核时的一些概念
- 【寒江雪】状态图和活动图
- 浙江理工大学2016年新生赛暨全国新生邀请赛H ZSTUOJ 4245: KI的斐波那契
- leetcode_75. Sort Colors题解
- 台州学院ACM:2506 An escape
- .htaccess 配置详解
- Freefloat FTP Server 1.0 溢出漏洞分析
- SpringCache(Spring使用Cache)
- Fragment 各种状态下的生命周期
- linux下安装php扩展memcache的方法
- arrayList, StringBuilder扩容的问题
- 电源篇-集成三端稳压器