Leetcode-455 分发饼干-贪心

在这里插入图片描述

既然要进行资源最优分配,自然想到要排序,child和cookie都从小到大,最小的(目前的)cookie比child(目前的)大,表明有能分得饼干的孩子加1(cookie++)

 public int findContentChildren(int[] g, int[] s) {
    
    
        //贪心算法,给局部最优使得全局最优
        //局部最优就是让每个孩子在满足条件的情况下得到最少的资源分配
        Arrays.sort(g);//底层是快速排序 nlogn
        Arrays.sort(s);
        int child=0; int cookie=0;
        while(child<g.length&&cookie<s.length){
    
     
            if(g[child]<=s[cookie]){
    
    
                ++child;
            }
            ++cookie;
        }
        return  child;

    }

猜你喜欢

转载自blog.csdn.net/WA_MC/article/details/115221288
今日推荐