455. 分发饼干

image.png
贪心的思想是,用尽量小的饼干去满足小需求的孩子,所以需要进行排序
思路都是对当前孩子和饼干按照升序排列

  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. func findContentChildren(g []int, s []int) int {
  7. if len(g)==0||len(s)==0 {
  8. return 0
  9. }
  10. sort.Ints(g)
  11. sort.Ints(s)
  12. var j = 0
  13. var child = 0
  14. for i :=0;i<len(g);i++{
  15. for ;j<len(s);j++{
  16. if g[i]<=s[j] {
  17. child ++
  18. j++
  19. break
  20. }
  21. }
  22. if len(s)==j {
  23. return child
  24. }
  25. }
  26. return child
  27. }
  28. func main() {
  29. g := []int{1,2,3}
  30. s := []int{1,1}
  31. fmt.Println(findContentChildren(g,s))
  32. g1 := []int{1,2}
  33. s1 := []int{1,2,3}
  34. fmt.Println(findContentChildren(g1,s1))
  35. g2 := []int{1,2,3}
  36. s2 := []int{3}
  37. fmt.Println(findContentChildren(g2,s2))
  38. }

image.png

简化版本

  1. func findContentChildren(g []int, s []int) int {
  2. if len(g)==0||len(s)==0 {
  3. return 0
  4. }
  5. sort.Ints(g)
  6. sort.Ints(s)
  7. var cookie =0
  8. var child = 0
  9. for cookie<len(s)&&child<len(g){
  10. if g[child]<=s[cookie] {
  11. child++
  12. }
  13. cookie++
  14. }
  15. return child
  16. }