算法训练|分配饼干(贪心算法)

贪心思想

用尽可能最小的成本解决最大的问题

在这里插入图片描述
解法1:

class Solution {
    
    
    public int findContentChildren(int[] g, int[] s) {
    
    
        Arrays.sort(g);
        Arrays.sort(s);
        int count = 0;
        int length1 = g.length;
        int length2 = s.length;
        for (int i = 0, j = 0; i < length1 && j < length2; i++, j++) {
    
    
            while (j<length2 && g[i]>s[j]) {
    
    
                j++;
            }
            if(j<length2){
    
    
                count++;
            }
        }
        return count;
    }
}

在这里插入图片描述
解法2:

class Solution {
    
    
    public int findContentChildren(int[] g, int[] s) {
    
    
        Arrays.sort(g);
        Arrays.sort(s);
        int child = 0;
        int cookies = 0;
        int length1 = g.length;
        int length2 = s.length;
        while(child <length1 && cookies<length2){
    
    
        //如果满足需求
            if(g[child]<=s[cookies]){
    
    
                child++;
            }
            //无论是否满足,饼干丢弃,一个饼干只用来比对一次,因为这是已经排序好的,如果小的需求都无法满足,则大的需求也无法满足。
            cookies++;
        }
        return child;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45394002/article/details/111660774