leetcode第十八周解题总结-贪心算法

455. Assign Cookies

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

题意解析: 典型的贪心问题,分曲奇,每个孩子至少分到一块,但是每个孩子都有贪心因子g,是他们满足的最小值,要求尽量满足更多的孩子。
解题思路:要满足更多的孩子,优先考虑满足贪心因子最小的孩子即可。

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        int n = g.size();
        int m = s.size();
        sort(g.begin(),g.end());
        sort(s.begin(),s.end());
        int counter = 0;

        for(int i=0,j=0; i <n&&j < m; j++) {
            if(g[i] <= s[j]) {
                counter ++;
                i ++;
            }
        }
        return counter;
    }
};

55. Jump Game

Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.

题意解析: 跳格子游戏,每个格子上的数字代表了在该位置能跳的最远距离。
解题思路:这道题也是贪心算法,记录当前能走到的位置,然后在范围内往前走,不断更新能到达的位置,最后判断是否已经到达结尾。

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int i = 0;
        for(int reach = 0; i <= reach&& i <nums.size(); i++){
            reach = max(nums[i] + i, reach);
        }
        return (i==nums.size());
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值