LeetCode (Sort Colors)
来源:互联网 发布:织梦 编辑器字体修改 编辑:程序博客网 时间:2024/04/26 10:11
Problem:
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 i = 0, n = nums.size(); while(i < n){ if(nums[i] == 0){ nums.erase(nums.begin() + i); nums.insert(nums.begin(), 0); i++; }else if(nums[i] == 1){ i++; }else{ nums.erase(nums.begin() + i); nums.push_back(2); n--; } } }};
Solution2:class Solution {public: void sortColors(vector<int>& nums) { int n0 = 0, n = nums.size() - 1; for(int i = 0; i <= n; i++){ if(nums[i] == 0) swap(nums[i], nums[n0++]); else if(nums[i] == 2) swap(nums[i--], nums[n--]); } }};
0 0
- LeetCode: Sort Colors
- LeetCode Sort Colors
- LeetCode : Sort Colors
- leetcode 77: Sort Colors
- Leetcode 75 Sort Colors
- leetcode 101: Sort Colors
- [LeetCode]Sort Colors
- [leetcode]Sort Colors
- LeetCode-Sort Colors
- [leetcode] Sort Colors
- [LeetCode] Sort Colors
- [leetCode] Sort Colors
- LeetCode - Sort Colors
- leetcode:Sort Colors
- LeetCode | Sort Colors
- 【LeetCode】Sort Colors
- Leetcode: Sort Colors
- [LeetCode] Sort Colors
- 记录linux安装nginx常见错误
- python高级特性之列表生成式
- 安卓手机兼职教程,下载应用试玩,每天2小时50块
- 顺序查找_Java
- php操作memcache
- LeetCode (Sort Colors)
- [OpenResty动态] 201705微信群
- opencv3.0.0 识别表格
- 利用fastjson解析即信语音json
- 友盟错误日志统计没有数据的问题
- 深入了解spring的ioc
- Arraylist动态扩容详解
- 折半查找_Java
- java调用HbaseAPI管理Hbase权限