美文网首页数据结构与算法
leetcode455.分发饼干

leetcode455.分发饼干

作者: 憨憨二师兄 | 来源:发表于2020-05-25 15:25 被阅读0次

    题目链接

    题目描述:

    假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。

    题解:贪心+双指针

    首先,我们对数组g和数组s进行排序;然后初始化指针gIndex与sIndex,每次分配饼干,都遵循一个原则:只关注未分配饼干的最小胃口的孩子,代码十分简单,如下所示:

    class Solution {
        public int findContentChildren(int[] g, int[] s) {
            Arrays.sort(g);
            Arrays.sort(s);
            int gIndex = 0;
            int sIndex = 0;
            while(gIndex < g.length && sIndex < s.length){
                if(g[gIndex] <= s[sIndex]){
                    gIndex++;
                }
                sIndex++;
            }
            return gIndex;
        }
    }
    

    时间复杂度:O(NlogN) 因为涉及到排序
    额外空间复杂度:O(1)

    执行结果:


    相关文章

      网友评论

        本文标题:leetcode455.分发饼干

        本文链接:https://www.haomeiwen.com/subject/nglyahtx.html