Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

455. 分发饼干 #25

Open
Geekhyt opened this issue Feb 5, 2021 · 0 comments
Open

455. 分发饼干 #25

Geekhyt opened this issue Feb 5, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 5, 2021

原题链接

贪心算法+双指针

  1. 给一个孩子的饼干应当尽量小并且能满足孩子,大的留来满足胃口大的孩子。
  2. 因为胃口小的孩子最容易得到满足,所以优先满足胃口小的孩子需求。
  3. 按照从小到大的顺序使用饼干尝试是否可满足某个孩子。
  4. 当饼干 j >= 胃口 i 时,饼干满足胃口,更新满足的孩子数并移动指针 gi++ sj++ res++
  5. 当饼干 j < 胃口 i 时,饼干不能满足胃口,需要换大的 sj++

关键点

将需求因子 g 和 s 分别从小到大进行排序,使用贪心思想,配合双指针,每个饼干只尝试一次,成功则换下一个孩子来尝试。

const findContentChildren = function (g, s) {
    g = g.sort((a, b) => a - b)
    s = s.sort((a, b) => a - b)
    let gi = 0 // 胃口值
    let sj = 0 // 饼干尺寸
    let res = 0
    while (gi < g.length && sj < s.length) {
        if (s[sj] >= g[gi]) {
            gi++
            sj++
            res++
        } else {
            sj++
        }
    }
    return res
}
  • 时间复杂度:O(nlogn)
  • 空间复杂度:O(1)
@Geekhyt Geekhyt added the 简单 label Jun 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant