Skip to content

Commit bea3254

Browse files
author
lucifer
committed
feat: $ 75
1 parent f95e13b commit bea3254

File tree

1 file changed

+33
-8
lines changed

1 file changed

+33
-8
lines changed

problems/75.sort-colors.md

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,23 +38,47 @@ https://leetcode-cn.com/problems/sort-colors/
3838

3939
## 思路
4040

41-
这个问题是典型的[荷兰国旗问题](https://en.wikipedia.org/wiki/Dutch_national_flag_problem) 因为我们可以将红白蓝三色小球想象成条状物,有序排列后正好组成荷兰国旗。
41+
这个问题是典型的荷兰国旗问题 ([https://en.wikipedia.org/wiki/Dutch_national_flag_problem)。](https://en.wikipedia.org/wiki/Dutch_national_flag_problem%EF%BC%89%E3%80%82) 因为我们可以将红白蓝三色小球想象成条状物,有序排列后正好组成荷兰国旗。
4242

43-
有两种解决思路。
44-
45-
## 解法一
43+
## 解法一 - 计数排序
4644

4745
- 遍历数组,统计红白蓝三色球(0,1,2)的个数
4846
- 根据红白蓝三色球(0,1,2)的个数重排数组
4947

50-
这种思路的时间复杂度:$O(n)$,需要遍历数组两次。
48+
这种思路的时间复杂度:$O(n)$,需要遍历数组两次(Two pass)。
49+
50+
![image](https://user-images.githubusercontent.com/12479470/83542989-4ef55100-a52e-11ea-9a49-a0e9443da5f4.png)
5151

52-
## 解法二
52+
## 解法二 - 挡板法
5353

5454
我们可以把数组分成三部分,前部(全部是 0),中部(全部是 1)和后部(全部是 2)三个部分。每一个元素(红白蓝分别对应 0、1、2)必属于其中之一。将前部和后部各排在数组的前边和后边,中部自然就排好了。
5555

5656
我们用三个指针,设置两个指针 begin 指向前部的末尾的下一个元素(刚开始默认前部无 0,所以指向第一个位置),end 指向后部开头的前一个位置(刚开始默认后部无 2,所以指向最后一个位置),然后设置一个遍历指针 current,从头开始进行遍历。
5757

58+
形象地来说地话就是有两个挡板,这两个挡板实现我们不知道,我们的目标就是移动挡板到合适位置,并且使得挡板每一部分都是合适的颜色。
59+
60+
![image](https://user-images.githubusercontent.com/12479470/83542469-9a5b2f80-a52d-11ea-990d-1b56623ba2c8.png)
61+
62+
还是以题目给的样例来说,初始化挡板位置为最左侧和最右侧:
63+
64+
![image](https://user-images.githubusercontent.com/12479470/83542548-b19a1d00-a52d-11ea-92aa-c2458d7fe178.png)
65+
66+
读取第一个元素是 2,它应该在右边,那么我们移动右边地挡板。
67+
68+
![image](https://user-images.githubusercontent.com/12479470/83542598-c5de1a00-a52d-11ea-9095-c66e1ed20c8f.png)
69+
70+
> 带有背景色的圆圈 1 是第一步的意思。
71+
72+
并将其和移动挡板后挡板右侧地元素进行一次交换,这意味着“被移动挡板右侧地元素已就位”。
73+
74+
![image](https://user-images.githubusercontent.com/12479470/83542711-e9a16000-a52d-11ea-9226-5a385c26174c.png)
75+
76+
。。。
77+
78+
整个过程大概是这样的:
79+
80+
![](https://tva1.sinaimg.cn/large/007S8ZIlly1ggssusgyj7j310m0l2td1.jpg)
81+
5882
这种思路的时间复杂度也是$O(n)$, 只需要遍历数组一次。
5983

6084
### 关键点解析
@@ -68,7 +92,7 @@ https://leetcode-cn.com/problems/sort-colors/
6892

6993
Python3 Code:
7094

71-
```python
95+
```py
7296
class Solution:
7397
def sortColors(self, nums: List[int]) -> None:
7498
"""
@@ -87,9 +111,10 @@ class Solution:
87111
p2 -= 1
88112
else:
89113
cur += 1
114+
90115
```
91116

92-
**复杂度分析**
117+
**_复杂度分析_**
93118

94119
- 时间复杂度:$O(N)$
95120
- 空间复杂度:$O(1)$

0 commit comments

Comments
 (0)