75. Sort Colors
来源:互联网 发布:sm2算法原理 编辑:程序博客网 时间:2024/06/17 23:48
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?
这道题的大致思路是遍历数组,把所有的0放到数组前面,把所有的2放到数组后面。思路比较容易,但实现起来需要仔细考虑一些细节。起初想用stl的数组操作的函数实现,出了很多问题,后来参考其他答案,找到了一个相对好理解的方法。
详解可以参考:Sharing C++ solution with Good Explanation
class Solution {public: void sortColors(vector<int>& nums) { /*分别用low,high,mid记录当前排序的状态,low之前是以及排号的0,high之后是已经排好的2,mid和high之间是尚未排序的数*/ int low = 0, high = nums.size() - 1, mid = 0; while (mid <= high) { if (nums[mid] == 0) { /*此时nums[mid]==0,nums[low]==1,两者交换*/ nums[mid] = nums[low]; nums[low] = 0; mid++; low++; } else if (nums[mid] == 2) { nums[mid] = nums[high]; nums[high] = 2; /*mid不能加一,因为交换之后nums[mid]可能等于0,还需要与nums[low]交换*/ high--; } else { mid++; } } }};
- 【sort专题】75. Sort Colors
- 75. Sort Colors
- [LeetCode]75.Sort Colors
- LeetCode --- 75. Sort Colors
- [Leetcode] 75. Sort Colors
- [leetcode] 75.Sort Colors
- 75. Sort Colors
- 【leetcode】75. Sort Colors
- 75. Sort Colors
- [leetcode] 75. Sort Colors
- Leetcode 75. Sort Colors
- *LeetCode 75. Sort Colors
- 75. Sort Colors LeetCode
- 75. Sort Colors
- Leetcode 75. Sort Colors
- 75. Sort Colors
- [LeetCode]75. Sort Colors
- 75. Sort Colors
- 鲜活的数据:数据可视化指南.pdf 免费下载
- Emacs使用monokai配色
- Data Science with Java Practical Methods for Scientists and Engineers.pdf 英文原版 免费下载
- markdown编辑器基本用法
- Rhyme/Hibernate load()与get()的区别
- 75. Sort Colors
- Jsp学习1-页面组成 指令 内置对象
- Pro Java Clustering and Scalability.pdf 英文原版 免费下载
- 时间都去哪了
- 2017年12月22日 第四十二天次总结
- C语言中二维数组名与数组地址、首行地址、首行首元素地址关系与区别详解(初学者必须掌握)
- Troubleshooting Java Performance.pdf 英文原版 免费下载
- 为Visual Studio添加默认INCLUDE包含路径的方法
- 冒泡排序剖析