代码随想录刷题第31天|LeetCode455分发饼干、LeetCode376摆动序列、LeetCode53最大子序和

1、LeetCode455 分发饼干

题目链接:455、分发饼干

饼干s = [1,1],胃口 g = [1,2,3]

思路一:大饼干满足大胃口

如果饼干不满足胃口,胃口要向前遍历去变小,再判断饼干是否能满足胃口,因此要对g遍历。

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());
        int result = 0;
        int index = s.size() - 1;
        for (int i = g.size() - 1; i >= 0; i--)
        {
            if (index >= 0 && s[index] >= g[i])
            {
                result++;
                index--;
            }
        }
        return result;
    }
};

思路二:小饼干满足小胃口

若小饼干满足不了小胃口,小饼干要向后遍历去变大,判断能否满足小胃口,因此对s饼干遍历。

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());
        int index = 0;
        for (int i = 0; i < s.size(); i++)
        {
            if (index < g.size() && s[i] >= g[index])
            {
                index++;
            }
        }
        return index;
    }
};

2、LeetCode376摆动序列

题目链接:376、摆动序列

考虑三种情况:

上下坡中有平坡,比如[12221],要么删除左边的两个2,要么删除右边的。可以统一规则删除左边的,(prediff <= 0 && curdiff > 0)  || (prediff >= 0 && curdiff < 0)。

首尾两端,第一个元素的prediff就假设为0,result 初始为 1(默认最右面有一个峰值)。

单调坡中有平坡,坡度摆动变化的时候,更新 prediff ,这样 prediff 在 单调区间有平坡的时候 就不会发生变化。

class Solution {
public:
    int wiggleMaxLength(vector<int>& nums) {
        int prediff = 0;
        int curdiff = 0;
        int result = 1;
        for (int i = 0; i < nums.size()-1; i++)
        {
            curdiff = nums[i+1] - nums[i];
            if ((prediff <= 0 && curdiff > 0) || (prediff >= 0 && curdiff < 0))
            {
                result++;
                prediff = curdiff;
            }
        }
        return result;
    }
};

3、LeetCode53最大子序和

题目链接:53、最大子数组和

如果连续和<= 0了,立刻放弃,从下一个元素重新计算“连续和”,因为负数加上下一个元素 “连续和”只会越来越小。

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int result = INT_MIN;
        int count = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            count += nums[i];

            result = count > result ? count : result;

            if (count <= 0)
            {
                count = 0;
            }
        }
        return result;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值