-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path75.颜色分类.py
More file actions
56 lines (55 loc) · 1.54 KB
/
75.颜色分类.py
File metadata and controls
56 lines (55 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#
# @lc app=leetcode.cn id=75 lang=python
#
# [75] 颜色分类
#
# https://leetcode-cn.com/problems/sort-colors/description/
#
# algorithms
# Medium (52.75%)
# Likes: 236
# Dislikes: 0
# Total Accepted: 33.8K
# Total Submissions: 63.9K
# Testcase Example: '[2,0,2,1,1,0]'
#
# 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
#
# 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
#
# 注意:
# 不能使用代码库中的排序函数来解决这道题。
#
# 示例:
#
# 输入: [2,0,2,1,1,0]
# 输出: [0,0,1,1,2,2]
#
# 进阶:
#
#
# 一个直观的解决方案是使用计数排序的两趟扫描算法。
# 首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
# 你能想出一个仅使用常数空间的一趟扫描算法吗?
#
#
#
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
red=white=0
blue=len(nums)-1
while white<=blue:
if nums[white]==0:
nums[white],nums[red]=nums[red],nums[white]
white+=1
red+=1
elif nums[white]==1:
white+=1
else:
nums[white]==2
nums[white],nums[blue]=nums[blue],nums[white]
blue-=1