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());
    }
};
    原文作者:贪心算法
    原文地址: https://blog.csdn.net/u013775900/article/details/74096015
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞