LeetCode 75 SortColor(Python详解及实现)
来源:互联网 发布:单片机的最小系统 编辑:程序博客网 时间:2024/04/29 14:37
【题目】
Given an array with n objects colored red,white or blue, sort them so that objects of the same color are adjacent, withthe colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library'ssort function for this problem.
click to show follow up.
Follow up:
A rather straight forward solution is atwo-pass algorithm using counting sort.
First, iterate the array counting number of0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's andfollowed by 2's.
Could you come up with an one-passalgorithm using only constant space?
给定n个颜色,红色,白色和蓝色。分别用0,1,2代替,将这些颜色排序,0在1前,1在2前。
注意:
不允许使用库函数。
遍历两遍数组,第一遍对0,1,2计数,第二遍对数组进行赋值。想出一种方法只使用常数空间,而且只能遍历一遍
【思路】
设置两个头尾指针,头指针pHead指向的位置是0该放置的位置,尾指针pTail指向的位置是2该放置的位置。i用来遍历整个数组,碰到0把它和pHead指向的数交换,碰到2把它和pTail指向的数交换,碰到1继续向后遍历。有点类似快速排序的分割数组这一步。
【Python实现】
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if nums == []:
return
pHead = 0
pTail = len(nums) - 1
i = 0
while i <= pTail :
if nums[i] == 2:
nums[i], nums[pTail ] = nums[pTail], nums[i]
pTail -= 1
elif nums[i] == 0:
nums[i], nums[pHead] =nums[pHead], nums[i]
pHead += 1
i += 1
else:
i += 1
#print(nums)
if __name__ == '__main__':
S= Solution()
matrix =[1,2,0,2,1,0,0,2,1,1,0]
S.sortColors( matrix)
- LeetCode 75 SortColor(Python详解及实现)
- LeetCode 65 ValidNumer(Python详解及实现)
- LeetCode 77 Combinations (Python详解及实现)
- LeetCode 78 Subsets (Python详解及实现)
- LeetCode 90 SubsetsII (Python详解及实现)
- LeetCode 55 Jump Game(Python 实现及详解)
- LeetCode 56 Merge Intervals(Python实现及详解)
- LeetCode 60 Permutation Sequence (Python实现及详解)
- LeetCode 61. Rotate List(Python详解及实现)
- LeetCode 66 Plus One (Python详解及实现)
- LeetCode 68 Text Justification(Python详解及实现)
- LeetCode 70 Climbing Stairs(Python详解及实现)
- LeetCode 71 Simplify Path(Python详解及实现)
- LeetCode 72 Edit Distance(Python详解及实现)
- LeetCode 73 Set Matrix Zeroes(Python详解及实现)
- LeetCode 76 Minimum Window Substring(Python详解及实现)
- LeetCode 79 Word Search (Python详解及实现)
- LeetCode 84 Largest Rectangle in Histogram (Python详解及实现)
- memset函数
- 西门子S7300PLC通过以太网连接组态王KingSCADA
- git中 rebase 和 revert
- 分析一个通用的rtsp server实现采集模块
- Linux From Scratch 构建自己的 Linux
- LeetCode 75 SortColor(Python详解及实现)
- 游历 JavaScript IoT 应用开发平台
- 基于阿里云的Jenkins+Maven+SVN+Tomcat的持续集成(一)--先前准备与jdk环境变量配置
- android程序中的AndroidManifest.xml中的uses-feature详解
- 吃货联盟订餐系统 java
- PHP MySQL Update
- php采集页面并自动转码
- 元素的水平及垂直居中实现方法二三
- 简单说 正则表达式——要注意lastIndex属性