[leetcode] Sort Colors
来源:互联网 发布:行知教育基地 编辑:程序博客网 时间:2024/06/06 05:35
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?
思路:
用类似quicksort的方法,进行一次遍历,在遍历过程中,遇到0就放在前面,遇到2就放在后面,然后把1夹在中间,从而成功排序
class Solution: # @param A a list of integers # @return nothing, sort in place def swap(self, index1, index2, A): tmp = A[index1] A[index1] = A[index2] A[index2] = tmp def sortColors(self, A): start = 0 end = len(A) - 1 while start < len(A) and A[start] == 0: start += 1 while end >= 0 and A[end] == 2: end -= 1 index = start while index <= end: if A[index] == 0: self.swap(start, index, A) start += 1 if start > index: index = start elif A[index] == 1: index += 1 elif A[index] == 2: self.swap(index, end, A) end -= 1 if A[index] == 0: self.swap(start, index, A) start += 1 if start > index: index = start
- 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
- Spring事务配置的五种方式
- android中使用Dialog实现目录选择器
- 如何配制MySql的Replication
- C#如何实现从内存中加载程序集
- 观察者模型
- [leetcode] Sort Colors
- Initialization error SQL * NET not properly installed OracleHomeKey: OracleHomeDir:等问题解决
- 实际使用中格式化输出以 % 打头,后跟以一个控制输出格式的字母。
- 苹果系统OSX中Automator批量重命名
- 最长公共子串(LCS)(连续与非连续)
- 此博客以后不再更新.....搬家啦
- LeetCode | Binary Tree Postorder Traversal
- Objective-c中Category的用法
- 代码杂项