(贪心01) 分发饼干 摆动序列 最大子数组和

一、分发饼干

力扣第455题

代码如下:

class Solution {
    public int findContentChildren(int[] g, int[] s) {
        int count = 0;
        int i = 0;
        int j = 0;
        Arrays.sort(g);
        Arrays.sort(s);
        while(i < g.length && j < s.length) {
            if(s[j] >= g[i]) {
                count ++;
                i++;
            }
            j++;
        }
        return count;
    }
}

时间复杂度:O(nlogn) 和排序有关

空间复杂度:O(1)

二、摆动序列

力扣第376题

注意:把每个元素当成折点,该点前后的折线增减关系用变量记录;

三种情况的考虑:

        1. 上下坡中有平坡

        2. 数组的首尾两端

        3. 单调坡中有平坡

代码如下:

class Solution {
    public int wiggleMaxLength(int[] nums) {
        if(nums.length <= 1) return nums.length;

        int prediff = 0; //前一对差值
        int curdiff = 0; //当前一对差值
        int count = 1; //记录峰值,最右边默认一个峰值

        for(int i = 0; i < nums.length - 1; i++) {
            curdiff = nums[i + 1] - nums[i];

            if(prediff >= 0 && curdiff < 0 || prediff <= 0 && curdiff > 0) {
                count++;
                prediff = curdiff;
            }
        }
        return count;
    }
}

时间复杂度:O(n);

空间复杂度:O(1);

三、最大子数组和

力扣第53题

难点:

        只要连续和还是正数就会对后面的元素起到增大总和的作用。 所以只要连续和为正数我们就保留。

代码如下:

class Solution {
    public int maxSubArray(int[] nums) {
        int result = Integer.MIN_VALUE;
        int count = 0;

        for(int i = 0; i < nums.length; i++) {
            count += nums[i];

            if(count > result) {
                result = count;
            }

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

时间复杂度:O(n)

空间复杂度:O(1)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值