leetcode 455. 分发饼干 简单 贪心算法

题目:
在这里插入图片描述

分析:题目很简单,尽可能满足越多数量的孩子,很明显的用到贪心算法的思想。只要从胃口最小的孩子开始满足,并且分给他刚好能满足他的饼干,那么就能实现最多的满足孩子。先对孩子胃口和饼干进行排序再进行循环,饼干分配过了就不再分配,而且这样也一定满足每个孩子最多一块饼干的条件。

代码:

class Solution {
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        boolean[] distribute = new boolean[s.length];
        int satisfy = 0;
        for(int i  = 0; i < g.length; i++){
            for(int j = 0; j < s.length; j++){
                if(!distribute[j] && s[j] >= g[i]){
                    distribute[j] = true;
                    satisfy++;
                    break;
                }
            }
        }
        return satisfy;
    }
}

在这里插入图片描述
在这里插入图片描述

发布了134 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_40208575/article/details/104718855