LeetCode
来源:互联网 发布:stm32f103rc数据手册 编辑:程序博客网 时间:2024/05/11 06:01
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.
有n个对象,值分别为0,1,2,现在希望对这n个对象进行排序,使得0在前,2在后。
嗯,循环交换。设立两个指针,一个指向开头,一个指向结尾,若是为0或是为2,即进行交换。时间复杂度O(n),空间复杂度O(1)
class Solution {public: void sortColors(vector<int>& nums) { if (nums.empty()) return; int zero = 0, second = nums.size() - 1; for (int i = 0; i <= second; ++i) { while (nums[i] == 2 && i < second) swap(nums[i], nums[second--]); while (nums[i] == 0 && i > zero) swap(nums[i], nums[zero++]); } return; }};
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- 撤销索引、撤销表以及撤销数据库
- jeecms系统使用介绍——通过二次开发实现对word、pdf、txt等上传附件的全文检索
- 用spark-submit启动Spark应用程序
- Lucene6.6之多索引+排序+多查询
- Java的静态分派和动态分派
- LeetCode
- UOJ147 [NOIP2015]斗地主 解题报告【搜索】【贪心】
- 如何绕过CDN找源站ip?
- vue.js存储--localStorage
- Python 运算符
- iOS 删除字符串中html标签
- 四、shell替换:变量、命令、转义字符的替换
- 数据可视化学习:使用API
- php面试题,各大企业常见的php面试题之三