leetcode: 75. Sort Colors
来源:互联网 发布:mac的话筒在哪 编辑:程序博客网 时间:2024/05/22 17:22
Q
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.
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?
AC
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ red, white, blue = 0, 0, len(nums)-1 while white <= blue: if nums[white] == 0: nums[red], nums[white] = nums[white], nums[red] white += 1 red += 1 elif nums[white] == 1: white += 1 else: nums[white], nums[blue] = nums[blue], nums[white] blue -= 1# Time: O(n)# Space: O(1)class Solution2(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ def triPartition(nums, target): i, j, n = 0, 0, len(nums) - 1 while j <= n: if nums[j] < target: nums[i], nums[j] = nums[j], nums[i] i += 1 j += 1 elif nums[j] > target: nums[j], nums[n] = nums[n], nums[j] n -= 1 else: j += 1 triPartition(nums, 1)if __name__ == "__main__": A = [2, 1, 1, 0, 0, 2] Solution().sortColors(A) assert A == [0, 0, 1, 1, 2, 2]
阅读全文
0 0
- [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
- 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
- 第五大周感想
- 使用ssh工具调用图形界面
- thinkphp5中__PUBLIC__的使用
- 代码重构(一)——总结代码的坏味道
- from scipy.linalg import _fblas ImportError: DLL load failed: 找不到指定的模块
- leetcode: 75. Sort Colors
- go 字符串的拼接
- 安装phpMyAdmin数据库图形管理
- C#多线程的基础整理(中)——Task和async await
- Codeforces 892/E Envy 最小生成树的query
- iOS开发-RuntimeDebug运行时源码调试(macOS APP)
- C#-动态编程
- .NET Entity Framework(EF)使用SqlQuery直接操作SQL查询语句或者执行过程
- C#获取本机MAC地址和IP