Leetcode-455 Distribute Cookies-Greedy

Insert picture description here

Since we want to allocate resources optimally, I naturally think of sorting, child and cookie are from small to large, the smallest (current) cookie is larger than child (current), indicating that there are children who can get cookies plus 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;

    }

Guess you like

Origin blog.csdn.net/WA_MC/article/details/115221288