From 6fa4ad4a91d5cbc80a7d98035a763e1afd2054e7 Mon Sep 17 00:00:00 2001 From: markwang Date: Tue, 30 Jul 2024 09:35:12 +0800 Subject: [PATCH] =?UTF-8?q?455.=E5=88=86=E5=8F=91=E9=A5=BC=E5=B9=B2?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0Go=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0455.分发饼干.md | 39 ++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md index 9f59d3ad..22dd7570 100644 --- a/problems/0455.分发饼干.md +++ b/problems/0455.分发饼干.md @@ -226,21 +226,36 @@ class Solution: ``` ### Go -```golang -//排序后,局部最优 + +版本一 大饼干优先 +```Go func findContentChildren(g []int, s []int) int { - sort.Ints(g) - sort.Ints(s) - - // 从小到大 - child := 0 - for sIdx := 0; child < len(g) && sIdx < len(s); sIdx++ { - if s[sIdx] >= g[child] {//如果饼干的大小大于或等于孩子的为空则给与,否则不给予,继续寻找选一个饼干是否符合 - child++ + sort.Ints(g) + sort.Ints(s) + index := len(s) - 1 + result := 0 + for i := len(g) - 1; i >= 0; i-- { + if index >= 0 && s[index] >= g[i] { + result++ + 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 } ```