leetcode 455.Assign Cookies【贪心】【easy】 | 刷题打卡

230 阅读1分钟

一、题目描述:

leetcode 455.Assign Cookies:假设你是一个很棒的家长,想给你的孩子一些饼干。但是每个孩子最多得到一块饼干。每个孩子i都有一个贪婪系数g[i],这是孩子们会满足的饼干的最小尺寸;每个饼干j都有一个尺寸s[j]。如果s[j]>=g[i],我们可以将饼干j分配给子i,那么孩子i将满足。您的目标是最大化满足的孩子的数量并输出最大数量。

二、思路分析:

1.类别

贪心

2.做题思路

这题是很典型的贪心,贪心的策略在于每次找要求最大的孩子,用最大的饼干满足他的需求,如果最大的饼干无法满足需求,那么就找要求次于最大的,按照这种策略直到孩子都有饼干或者直到饼干无法再被分完。

贪心的思路很好想,但是这里重点记录一个我的错误:

class Solution
{
public:
    static bool cmp(int a, int b){
        return a > b;
    }
    int findContentChildren(vector<int> &g, vector<int> &s){
        sort(g.begin(), g.end(), cmp);
        sort(s.begin(), s.end(), cmp);
        vector<int>::iterator s_it = s.begin();
        int res = 0;
        for (vector<int>::iterator g_it = g.begin(); g_it != g.end(); g_it++){
            if (s_it == s.end())
                break;
            while (*g_it > *s_it && g_it != g.end())
                g_it++;
            if (*g_it <= *s_it)
            {
                res++;
                s_it++;
            }
        }
        return res;
    }
};

![image.png](https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b4589e1245894ee088a01d47ae4eb924~tplv-k3u1fbpfcp-watermark.image)

以上代码看起来没有大错,但是最后一个样例怎么也通不过,最后发现是由于g_it++有可能会执行两次,因为for循环再执行完循环体后,再执行g_it++,然后才判断中间的语句,所以这样会发生g中的元素被跳过的情况,因此没办法AC。

所以这里是一个经验:如果循环体里面会改变循环变量的值,就像在这里g_it会在循环体里面被改变,最好不要用for循环,直接用while循环会比较好。

三、AC 代码:

class Solution
{
public:
    static bool cmp(int a, int b){
        return a > b;
    }
    int findContentChildren(vector<int> &g, vector<int> &s){
        sort(g.begin(), g.end(), cmp);
        sort(s.begin(), s.end(), cmp);
        vector<int>::iterator s_it = s.begin();
        vector<int>::iterator g_it = g.begin();
        int res = 0;
        while(g_it!=g.end()){
            if (s_it == s.end())
                break;
            if (*g_it <= *s_it)
            {
                res++;
                s_it++;
                g_it++;
            }
            else{
                g_it++;
            }
        } 
        return res;
    }
};

四、总结

leetcode 贪心相关的题目:

  • leetcode 45
  • leetcode 122 (未来填坑)

本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情