[Leetcode] 75. Sort Colors 解题报告
来源:互联网 发布:淘宝美工岗位 编辑:程序博客网 时间:2024/06/03 21:33
题目:
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?
思路:
发现自己原来写的代码就是两遍扫描,感觉好low。一遍扫描需要维持三个关键索引:1)left:left左边的值都应该是0;2)right:right右边的值都应该是2;3)i:当前的扫描位置。每次扫描碰到0,则和left交换位置并且left右移一位;碰到2,则和right交换位置并且right左移一位(注意此时扫描位置i不能前进,因为我们不知道从right处交换过来的值是0还是1)。
代码:
class Solution {public: void sortColors(vector<int>& nums) { if(nums.size() == 0) return; int i = 0, left = 0, right = nums.size() - 1; while(i <= right) { if(nums[i] == 2) swap(nums[i], nums[right--]); else { if(nums[i] == 0) swap(nums[left++], nums[i]); i++; } } }};
- [leetcode] 75. Sort Colors 解题报告
- leetcode解题报告:75. Sort Colors
- [Leetcode] 75. Sort Colors 解题报告
- 【LeetCode】Sort Colors 解题报告
- [LeetCode] Sort Colors 解题报告
- Leetcode 75. Sort Colors 色彩排序 解题报告
- leetCode 75.Sort Colors (颜色排序) 解题思路和方法
- [LeetCode]75.Sort Colors
- LeetCode --- 75. Sort Colors
- [Leetcode] 75. Sort Colors
- [leetcode] 75.Sort Colors
- 【leetcode】75. Sort Colors
- [leetcode] 75. Sort Colors
- Leetcode 75. Sort Colors
- *LeetCode 75. Sort Colors
- 75. Sort Colors LeetCode
- Leetcode 75. Sort Colors
- [LeetCode]75. Sort Colors
- 讲一讲WiFi快连、SmartConfig、SmartConnect
- $(document)与$(window)的区别
- ARM:嵌入式系统介绍、开发板环境设置、tftp实现文件下载、SecureCRT工具烧写
- Spring Web MVC框架(一) 搭建环境
- 整理--linux设备驱动模型
- [Leetcode] 75. Sort Colors 解题报告
- java----接口
- 整理--platform平台总线
- 系统启动时在bus系统中注册platform总线
- Permutation Sequence
- Mac OS X下进行网络抓包
- angularjs 依赖压缩以及自定义过滤器写法
- 九度OJ-1124-Digital Roots
- LeetCode 501. Find Mode in Binary Search Tree