Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6fa4ad4

Browse files
455.分发饼干增加Go解法
1 parent 0473a9b commit 6fa4ad4

File tree

1 file changed

+27
-12
lines changed

1 file changed

+27
-12
lines changed

‎problems/0455.分发饼干.md‎

Lines changed: 27 additions & 12 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /