Skip to content

Commit 770b5ee

Browse files
aQuaaQua
aQua
authored and
aQua
committed
75 finish
1 parent 74eaea0 commit 770b5ee

File tree

2 files changed

+30
-33
lines changed

2 files changed

+30
-33
lines changed

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

Lines changed: 19 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -6,54 +6,40 @@ func sortColors(nums []int) {
66
return
77
}
88

9-
if only2 := setHead(nums); only2 {
10-
return
11-
}
9+
// 三路快排需要 nums[0] == 1
10+
temp := nums[0]
11+
nums[0] = 1
1212

1313
// 三路快排
14+
// 排序完成后,
15+
// i 指向 0 后的 1,
16+
// j 指向 最后一个 1 后面的位置,
17+
// k 指向 2 前面的 1,
18+
// 在整个排序过程中,nums[i:j]中始终都是1
1419
i, j, k := 0, 1, length-1
1520
for j <= k {
1621
switch {
17-
case nums[j] < nums[i]:
22+
case nums[j] < 1:
23+
// 比 1 小的,放入队列首部
1824
nums[i], nums[j] = nums[j], nums[i]
1925
i++
2026
j++
21-
case nums[i] < nums[j]:
27+
case 1 < nums[j]:
28+
// 比 1 大的,放入队列尾部
2229
nums[j], nums[k] = nums[k], nums[j]
2330
k--
2431
default:
2532
j++
2633
}
2734
}
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-
}
4435

45-
// nums 中没有 1
46-
// 只好设置 nums[0] = 0
47-
i = 0
48-
for i < l && nums[i] != 0 {
49-
i++
36+
// 分情况,还原temp
37+
switch temp {
38+
case 0:
39+
nums[i] = temp
40+
case 2:
41+
nums[k] = temp
5042
}
5143

52-
if i < l {
53-
nums[0], nums[i] = nums[i], nums[0]
54-
return false
55-
}
56-
57-
// nums 中只有 2
58-
return true
44+
return
5945
}

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,16 @@ func Test_Problem0075(t *testing.T) {
5353
[]int{0, 0, 0, 1, 1, 1, 2, 2, 2},
5454
},
5555
},
56+
57+
question{
58+
para{
59+
[]int{2, 1},
60+
},
61+
ans{
62+
[]int{1, 2},
63+
},
64+
},
65+
5666
question{
5767
para{
5868
[]int{},
@@ -61,6 +71,7 @@ func Test_Problem0075(t *testing.T) {
6171
[]int{},
6272
},
6373
},
74+
6475
question{
6576
para{
6677
[]int{2, 2, 2, 2, 2, 2},

0 commit comments

Comments
 (0)