力扣01之分发饼干

链接:分发饼干

解法1:优先喂饱胃口大的小朋友

class Solution {
    public static int findContentChildren(int[] g, int[] s) {
        // 思路:优先喂饱胃口大的孩子,以免造成浪费
        // step1. 从小到大排序胃口和饼干的大小
        Arrays.sort(g);
        Arrays.sort(s);
        // step2.一个变量用于计数(>=0);另一个变量当作指针,指示剩余的饼干量(>=0,可以等于0,数组0位置仍存着一块饼干)
        int count = 0;
        int start = s.length - 1;
        // step3. 从后往前统计剩余的饼干,因为大饼干先分给胃口大的,接着依次分配。
        for (int i = g.length - 1; i >= 0; i--) {
            // step4. 如果还剩余饼干且这块饼干大于这个小孩的胃口,那么就将这块饼干分给这个小朋友,指针往前指一位,满足的小朋友也+1
            if (start >= 0 && g[i] <= s[start]) {
                start--;
                count++;
            }
        }
        return count;

    }

}

解法2:优先喂饱胃口小的小朋友

public static int findContentChildren(int[] g, int[] s) {
        // 思路2:先喂饱胃口小的小朋友
        // step1 从小到大排序胃口和饼干的大小
        Arrays.sort(g);
        Arrays.sort(s);
        // step2. 一个变量用于计数(>=0);另一个变量当作饼干指针,指示当前第几块饼干
        int count = 0;
        int start = 0;
        // step3. 从前往后分配饼干,只要饼干分量大于小朋友的胃口,就将其喂给小朋友,这里要注意start < g.length(若小朋友都分配到了饼干就应当结束循环)
        for (int i = 0; i < s.length && start < g.length; i++) {
            if(s[i] >= g[start]) {
                count++;
                start++;
            }
        }
        return count;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值