Leetcode 75. Sort Colors (Medium) (cpp)
2016-07-27 16:55
519 查看
Leetcode 75. Sort Colors (Medium) (cpp)
Tag: Array, Two Pointers, Sort
Difficulty: Medium
Tag: Array, Two Pointers, Sort
Difficulty: Medium
/* 75. Sort Colors (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? */ class Solution { public: void sortColors(vector<int>& nums) { int left = 0, mid = 0, right = nums.size() - 1; while (mid <= right) { if (nums[mid] == 0) swap(nums[left++], nums[mid++]); else if (nums[mid] == 2) swap(nums[mid], nums[right--]); else mid++; } } };
相关文章推荐
- [C++]高效使用c++11的一些建议
- C语言合并数组
- c++ const
- C语言读取数组长度
- C++ Block(代码块)
- c语言的学习
- Codeforces 427C - Checkposts 极大连通分量Tarjan算法模板题(STL实现)
- 第18周 C语言实战105例 实例4:逻辑运算符计算器
- [PAT(B)]1006. 换个格式输出整数 (15)源码
- Leetcode 34. Search for a Range (Medium) (cpp)
- strstr()的实现
- C语言关键字
- 【C/C++】用递归实现字符串逆序
- 全排列与next_permutation
- c++如何调用lib文件 静态库文件
- C语言的数据类型
- C++命名规则
- 继续c++吧。
- UVA 10050-Hartals
- 装饰模式C++实现