Skip to content

Commit 42ac6d4

Browse files
add Solution 455 [golang]
1 parent c69bac4 commit 42ac6d4

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/* 455 分发饼干
2+
* 解法
3+
* 每个小朋友只能最多拥有一块饼干,先满足胃口最大的小孩,剩下的就更容易分配
4+
* 由于题目没有预先给 g、s 进行排序,需要自己实现快速排序,这里利用goroutine并行运算加速
5+
*
6+
* 21/21 cases passed (40 ms)
7+
* memory usage (6 MB)
8+
*/
9+
10+
func findContentChildren(g []int, s []int) int {
11+
done1 := make(chan struct{})
12+
done2 := make(chan struct{})
13+
go quickSort_go(g, 0, len(g)-1, done1, 4)
14+
go quickSort_go(s, 0, len(s)-1, done2, 4)
15+
<-done1
16+
<-done2
17+
i, j, ret := len(g)-1, len(s)-1, 0
18+
for i >= 0 && j >= 0 {
19+
if g[i] > s[j] {
20+
i--
21+
} else {
22+
ret++
23+
i--
24+
j--
25+
}
26+
}
27+
return ret
28+
}
29+
30+
* 快速排序
31+
func quickSort(a []int, lo, hi int) {
32+
if lo >= hi {
33+
return
34+
}
35+
p := partition(a, lo, hi)
36+
quickSort(a, lo, p-1)
37+
quickSort(a, p+1, hi)
38+
}
39+
func partition(a []int, lo, hi int) int {
40+
pivot := a[hi]
41+
i := lo - 1
42+
for j := lo; j < hi; j++ {
43+
if a[j] < pivot {
44+
i++
45+
a[j], a[i] = a[i], a[j]
46+
}
47+
}
48+
a[i+1], a[hi] = a[hi], a[i+1]
49+
return i + 1
50+
}
51+
func quickSort_go(a []int, lo, hi int, done chan struct{}, depth int) {
52+
if lo >= hi {
53+
done <- struct{}{}
54+
return
55+
}
56+
depth--
57+
p := partition(a, lo, hi)
58+
if depth > 0 {
59+
childDone := make(chan struct{}, 2)
60+
go quickSort_go(a, lo, p-1, childDone, depth)
61+
go quickSort_go(a, p+1, hi, childDone, depth)
62+
<-childDone
63+
<-childDone
64+
} else {
65+
quickSort(a, lo, p-1)
66+
quickSort(a, p+1, hi)
67+
}
68+
done <- struct{}{}
69+
}

0 commit comments

Comments
 (0)