Skip to content

Commit 74eaea0

Browse files
aQuaaQua
aQua
authored and
aQua
committed
75 accepted,耗时3ms,最快的耗时0ms
1 parent 5e56bdd commit 74eaea0

File tree

2 files changed

+89
-2
lines changed

2 files changed

+89
-2
lines changed
Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,59 @@
11
package Problem0075
22

3-
func sortColors(nums []int) {
3+
func sortColors(nums []int) {
4+
length := len(nums)
5+
if length == 0 {
6+
return
7+
}
48

9+
if only2 := setHead(nums); only2 {
10+
return
11+
}
12+
13+
// 三路快排
14+
i, j, k := 0, 1, length-1
15+
for j <= k {
16+
switch {
17+
case nums[j] < nums[i]:
18+
nums[i], nums[j] = nums[j], nums[i]
19+
i++
20+
j++
21+
case nums[i] < nums[j]:
22+
nums[j], nums[k] = nums[k], nums[j]
23+
k--
24+
default:
25+
j++
26+
}
27+
}
28+
return
29+
}
30+
31+
// 如果 nums 中有 1 , nums[0] 应该为 1
32+
// 否则,如果 nums 中还有 0, nums[0] 应该为 0
33+
// 否则,说明 nums 中只有 2。
34+
func setHead(nums []int) bool {
35+
i, l := 0, len(nums)
36+
// 设置 nums[0] = 1
37+
for i < l && nums[i] != 1 {
38+
i++
39+
}
40+
if i < l {
41+
nums[0], nums[i] = nums[i], nums[0]
42+
return false
43+
}
44+
45+
// nums 中没有 1
46+
// 只好设置 nums[0] = 0
47+
i = 0
48+
for i < l && nums[i] != 0 {
49+
i++
50+
}
51+
52+
if i < l {
53+
nums[0], nums[i] = nums[i], nums[0]
54+
return false
55+
}
56+
57+
// nums 中只有 2
58+
return true
559
}

Algorithms/0075.sort-colors/sort-colors_test.go

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,24 @@ func Test_Problem0075(t *testing.T) {
2727

2828
qs := []question{
2929

30+
question{
31+
para{
32+
[]int{0, 2, 0, 2, 0, 2},
33+
},
34+
ans{
35+
[]int{0, 0, 0, 2, 2, 2},
36+
},
37+
},
38+
39+
question{
40+
para{
41+
[]int{1, 2, 1, 2, 1, 2},
42+
},
43+
ans{
44+
[]int{1, 1, 1, 2, 2, 2},
45+
},
46+
},
47+
3048
question{
3149
para{
3250
[]int{0, 1, 2, 0, 1, 2, 0, 1, 2},
@@ -35,7 +53,22 @@ func Test_Problem0075(t *testing.T) {
3553
[]int{0, 0, 0, 1, 1, 1, 2, 2, 2},
3654
},
3755
},
38-
56+
question{
57+
para{
58+
[]int{},
59+
},
60+
ans{
61+
[]int{},
62+
},
63+
},
64+
question{
65+
para{
66+
[]int{2, 2, 2, 2, 2, 2},
67+
},
68+
ans{
69+
[]int{2, 2, 2, 2, 2, 2},
70+
},
71+
},
3972
// 如需多个测试,可以复制上方元素。
4073
}
4174

0 commit comments

Comments
 (0)