贪心算法 455

455. 分发饼干

class Solution {
    public int findContentChildren(int[] g, int[] s) {

        Arrays.sort(g); //孩子列表
        Arrays.sort(s); //饼干列表
        int start=0;  //先把饼干和孩子从小到大排好序
        for(int i=0;i<s.length&&start<g.length;i++){ //先满足胃口小的孩子 从小到大顺序来      
            if(s[i]>=g[start]){				
                start++;
            }
        }
        return start;
    }
}
class Solution {
    public int findContentChildren(int[] g, int[] s) {

        Arrays.sort(g); //孩子列表
        Arrays.sort(s); //饼干列表        
        int start=s.length-1;
        int count=0;
        for(int i=g.length-1;i>=0&&start>=0;i--){ //遍历孩子    (外加条件 饼干还有的情况下继续遍历)
            if(s[start]>=g[i]){
                start--;
                count++;
            }
        }
        return count;
    }
}



posted on 2022-10-23 13:24  你是千堆雪我是长街7  阅读(11)  评论(0)    收藏  举报

导航