分发饼干(LeetCode455)---排序和贪心(Java)

该文章已生成可运行项目,

请添加图片描述
贪心算法:先寻找局部最优解,进而整合起来的结果仍然是整体最优解。将饼干按照从小到大排列,同时也将孩子的胃口从小到大排序,找到满足孩子胃口的最小饼干,满足这个局部最优解。
请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述

class Solution {
    public int findContentChildren(int[] g, int[] s) {
    		//将孩子们的胃口进行排序
            Arrays.sort(g);
            //将饼干的大小进行排序
            Arrays.sort(s);
            //当前遍历到的饼干
            int cookie = 0;
            //有多少个孩子得到满足了
            int child = 0;
            //饼干没有遍历完或者孩子的胃口没有满足完
            while (cookie < s.length && child < g.length){
                //当前遍历到的饼干的大小 大于等于孩子的胃口
                if (g[child] <= s[cookie]){
                    //那么有有个孩子可以得到满足
                    child++;
                }
                //当前遍历到的饼干的大小 小于孩子的胃口,继续往后遍历饼干
                cookie++;
            }
            return child;
    }
}
本文章已经生成可运行项目
### LeetCode - 455 分发饼干 以下是使用 C 语言实现的代码,运用贪心算法,通过对孩子胃口饼干大小数组排序,然后依次匹配: ```c // qsort()函数的比较函数,升序排列 int cmp(const void* a, const void* b) { return *((int*)a) - *((int*)b); } int findContentChildren(int* g, int gSize, int* s, int sSize) { // 对两个数组排序 qsort(g, gSize, sizeof(int), cmp); qsort(s, sSize, sizeof(int), cmp); int i = 0, j = 0; int count = 0; while (i < gSize && j < sSize) { if (s[j] >= g[i]) { ++count; ++i; ++j; } else { ++j; } } return count; } ``` ### LeetCode - 55 跳跃游戏(1) 该问题判断是否能够到达数组的最后一个位置,使用贪心算法,记录当前能到达的最远位置: ```c #include <stdbool.h> bool canJump(int* nums, int numsSize) { int maxReach = 0; for (int i = 0; i < numsSize; i++) { if (i > maxReach) { return false; } maxReach = (i + nums[i]) > maxReach ? (i + nums[i]) : maxReach; if (maxReach >= numsSize - 1) { return true; } } return false; } ``` ### LeetCode - 45 跳跃游戏(2) 此问题是求到达数组最后一个位置的最少跳跃次数,同样使用贪心算法,记录当前跳跃能到达的边界下一步能到达的最远位置: ```c int jump(int* nums, int numsSize) { if (numsSize < 2) { return 0; } int jumps = 0; int currentEnd = 0; int farthest = 0; for (int i = 0; i < numsSize - 1; i++) { farthest = (i + nums[i]) > farthest ? (i + nums[i]) : farthest; if (i == currentEnd) { jumps++; currentEnd = farthest; } } return jumps; } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值