forked from yijizhichang/LeetCodeInGo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path75.go
More file actions
42 lines (35 loc) · 1.09 KB
/
75.go
File metadata and controls
42 lines (35 loc) · 1.09 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
package problem
/*
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
进阶:
一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
你能想出一个仅使用常数空间的一趟扫描算法吗?
*/
func sortColors(nums []int) {
if len(nums) == 0 {
return
}
p0 := 0
p2 := len(nums) - 1
curr := 0
for curr <= p2 {
switch nums[curr] {
case 0:
nums[p0],nums[curr] = nums[curr],nums[p0]
p0++
curr++
case 1:
curr++
case 2:
nums[p2],nums[curr] = nums[curr],nums[p2]
p2--
}
}
}