Skip to content

Commit 775f8c6

Browse files
Merge pull request youngyangyang04#2653 from markwang1992/455-findContentChildren
455.分发饼干增加Go解法
2 parents d97ed82 + 6fa4ad4 commit 775f8c6

File tree

1 file changed

+27
-12
lines changed

1 file changed

+27
-12
lines changed

problems/0455.分发饼干.md

+27-12
Original file line numberDiff line numberDiff line change
@@ -226,21 +226,36 @@ class Solution:
226226
```
227227

228228
### Go
229-
```golang
230-
//排序后,局部最优
229+
230+
版本一 大饼干优先
231+
```Go
231232
func findContentChildren(g []int, s []int) int {
232-
sort.Ints(g)
233-
sort.Ints(s)
234-
235-
// 从小到大
236-
child := 0
237-
for sIdx := 0; child < len(g) && sIdx < len(s); sIdx++ {
238-
if s[sIdx] >= g[child] {//如果饼干的大小大于或等于孩子的为空则给与,否则不给予,继续寻找选一个饼干是否符合
239-
child++
233+
sort.Ints(g)
234+
sort.Ints(s)
235+
index := len(s) - 1
236+
result := 0
237+
for i := len(g) - 1; i >= 0; i-- {
238+
if index >= 0 && s[index] >= g[i] {
239+
result++
240+
index--
241+
}
240242
}
241-
}
243+
return result
244+
}
245+
```
242246

243-
return child
247+
版本二 小饼干优先
248+
```Go
249+
func findContentChildren(g []int, s []int) int {
250+
sort.Ints(g)
251+
sort.Ints(s)
252+
index := 0
253+
for i := 0; i < len(s); i++ {
254+
if index < len(g) && g[index] <= s[i] {
255+
index++
256+
}
257+
}
258+
return index
244259
}
245260
```
246261

0 commit comments

Comments
 (0)