代码随想录算法训练营第三十一天 | 455.分发饼干、376. 摆动序列、53. 最大子序和

455.分发饼干

题目链接:https://leetcode.cn/problems/assign-cookies/
文档讲解:https://programmercarl.com/0455.%E5%88%86%E5%8F%91%E9%A5%BC%E5%B9%B2.html
视频讲解:https://www.bilibili.com/video/BV1MM411b7cq

思路

  • 基本的思路是让大饼干优先喂饱大胃口。
  • 首先对胃口和饼干都进行排序,然后从后往前进行比较,如果饼干大小大于等于胃口,res++
  • 注意不能先遍历饼干再遍历胃口。

代码

class Solution {
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int res = 0;
        int index = s.length - 1; // 记录饼干的下标
        for (int i = g.length - 1; i >= 0; i--) { // 遍历胃口
            if (index >= 0 && s[index] >= g[i]) { // 饼干大于等于胃口,就成功匹配一个
                res++;
                index--;
            }
        }
        return res;
    }
}

分析:时间复杂度:O(nlogn);空间复杂度:O(1)。
时间复杂度主要由排序步骤决定,其中ng数组和s数组中的元素数量。

  1. Arrays.sort(g); 的时间复杂度为 O(n log n)
  2. Arrays.sort(s); 的时间复杂度为 O(n log n)
  3. 遍历两个数组寻找匹配的时间复杂度为 O(n)
    由于排序步骤是算法中时间复杂度最高的部分,因此整段代码的时间复杂度是O(n log n)

376. 摆动序列

题目链接:https://leetcode.cn/problems/wiggle-subsequence/
文档讲解:https://programmercarl.com/0376.%E6%91%86%E5%8A%A8%E5%BA%8F%E5%88%97.html
视频讲解:https://www.bilibili.com/video/BV17M411b7NS

思路

本题的摆动可以分为三种情况:

  • 上下有平坡
    preDiff == 0curDiff大于或小于0时,也认为是一个摆动。
if ((preDiff >= 0 && curDiff < 0) || (preDiff <= 0 && curDiff > 0)) {
  • 首尾元素
    将结果res初始化为1,默认右边是有摆动的。
  • 单调有平坡
    当有摆动时再更新preDiff的值,而不是遍历一个元素就更新,这样就会跳过单调平坡的情况。
if ((preDiff >= 0 && curDiff < 0) || (preDiff <= 0 && curDiff > 0)) {
        res++;
        preDiff = curDiff;
}

代码

class Solution {
    public int wiggleMaxLength(int[] nums) {
        int preDiff = 0, curDiff = 0, res = 1;
        for (int i = 0; i < nums.length; i++) {
            if (i > 0) curDiff = nums[i - 1] - nums[i];
            if ((preDiff >= 0 && curDiff < 0) || (preDiff <= 0 && curDiff > 0)) {
                res++;
                preDiff = curDiff;
            }
        }
        return res;
    }
}

分析:时间复杂度:O(n);空间复杂度:O(1)。

376. 摆动序列

题目链接:https://leetcode.cn/problems/maximum-subarray/
文档讲解:https://programmercarl.com/0053.%E6%9C%80%E5%A4%A7%E5%AD%90%E5%BA%8F%E5%92%8C.html
视频讲解:https://www.bilibili.com/video/BV1aY4y1Z7ya

思路

res来记录累加的最大值。当累加和小于0时,如果它加上后面的数,就会让后面的数变小,所以这是就把sum归零,从下一个数重新寻找子序列。

代码

class Solution {
    public int maxSubArray(int[] nums) {
        int res = Integer.MIN_VALUE;
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            res = Math.max(res, sum);
            if (sum < 0) sum = 0;
        }
        return res;
    }
}

分析:时间复杂度:O(n);空间复杂度:O(1)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值