File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ *** 给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums ,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。***
2
+
3
+ ```
4
+ 单指针+对数组进行两次遍历。在第一次遍历中,我们将数组中所有的 0 交换到数组的头部。在第二次遍历中,我们将数组中所有的 1 交换到头部的 0 之后。此时,所有的 2 都出现在数组的尾部,这样我们就完成了排序。
5
+ class Solution:
6
+ def sortColors(self, nums: List[int]) -> None:
7
+ """
8
+ Do not return anything, modify nums in-place instead.
9
+ """
10
+ n = len(nums)
11
+ ptr = 0
12
+ for i in range(n):
13
+ if nums[i] == 0:
14
+ nums[i], nums[ptr] = nums[ptr], nums[i]
15
+ ptr += 1
16
+ for i in range(ptr, n):
17
+ if nums[i] == 1:
18
+ nums[i], nums[ptr] = nums[ptr], nums[i]
19
+ ptr += 1
20
+ return nums
21
+ ```
22
+
23
+ ```
24
+ 双指针Ref:https://leetcode.cn/problems/sort-colors/solution/yan-se-fen-lei-by-leetcode-solution/
25
+ class Solution:
26
+ def sortColors(self, nums: List[int]) -> None:
27
+ """
28
+ Do not return anything, modify nums in-place instead.
29
+ """
30
+ n = len(nums)
31
+ p0 = p1 = 0
32
+ for i in range(n):
33
+ if nums[i] == 0:
34
+ nums[i], nums[p0] = nums[p0], nums[i]
35
+ if p0 < p1:
36
+ nums[i], nums[p1] = nums[p1], nums[i]
37
+ p0 += 1
38
+ p1 += 1
39
+ elif nums[i] == 1:
40
+ nums[i], nums[p1] = nums[p1], nums[i]
41
+ p1 += 1
42
+ ```
You can’t perform that action at this time.
0 commit comments