mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
455.分发饼干增加Go解法
This commit is contained in:
@ -226,21 +226,36 @@ class Solution:
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Go
|
### Go
|
||||||
```golang
|
|
||||||
//排序后,局部最优
|
版本一 大饼干优先
|
||||||
|
```Go
|
||||||
func findContentChildren(g []int, s []int) int {
|
func findContentChildren(g []int, s []int) int {
|
||||||
sort.Ints(g)
|
sort.Ints(g)
|
||||||
sort.Ints(s)
|
sort.Ints(s)
|
||||||
|
index := len(s) - 1
|
||||||
// 从小到大
|
result := 0
|
||||||
child := 0
|
for i := len(g) - 1; i >= 0; i-- {
|
||||||
for sIdx := 0; child < len(g) && sIdx < len(s); sIdx++ {
|
if index >= 0 && s[index] >= g[i] {
|
||||||
if s[sIdx] >= g[child] {//如果饼干的大小大于或等于孩子的为空则给与,否则不给予,继续寻找选一个饼干是否符合
|
result++
|
||||||
child++
|
index--
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
return result
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
return child
|
版本二 小饼干优先
|
||||||
|
```Go
|
||||||
|
func findContentChildren(g []int, s []int) int {
|
||||||
|
sort.Ints(g)
|
||||||
|
sort.Ints(s)
|
||||||
|
index := 0
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
if index < len(g) && g[index] <= s[i] {
|
||||||
|
index++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return index
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user