455. 分发饼干
贪心的思想是,用尽量小的饼干去满足小需求的孩子,所以需要进行排序
思路都是对当前孩子和饼干按照升序排列
package main
import (
"fmt"
"sort"
)
func findContentChildren(g []int, s []int) int {
if len(g)==0||len(s)==0 {
return 0
}
sort.Ints(g)
sort.Ints(s)
var j = 0
var child = 0
for i :=0;i<len(g);i++{
for ;j<len(s);j++{
if g[i]<=s[j] {
child ++
j++
break
}
}
if len(s)==j {
return child
}
}
return child
}
func main() {
g := []int{1,2,3}
s := []int{1,1}
fmt.Println(findContentChildren(g,s))
g1 := []int{1,2}
s1 := []int{1,2,3}
fmt.Println(findContentChildren(g1,s1))
g2 := []int{1,2,3}
s2 := []int{3}
fmt.Println(findContentChildren(g2,s2))
}
简化版本
func findContentChildren(g []int, s []int) int {
if len(g)==0||len(s)==0 {
return 0
}
sort.Ints(g)
sort.Ints(s)
var cookie =0
var child = 0
for cookie<len(s)&&child<len(g){
if g[child]<=s[cookie] {
child++
}
cookie++
}
return child
}