算法训练Day31|理论基础 ● 455.分发饼干 ● 376. 摆动序列 ● 53. 最大子序和

理论基础

代码随想录 (programmercarl.com)

贪心:局部最优,推出整体最优。
常识逻辑顺序推导/找不出反例

LeetCode:455.分发饼干

455. 分发饼干 - 力扣(LeetCode)

1.思路

题目示例都是有序的,不排序也能实现,但没有明确说明是有序的,提前拍个序比较稳妥.
①双层for循环暴力解法,遇到符合条件的用break终止本层for循环,返回计数器结果即可.

2.代码实现
 1class Solution {
 2    public int findContentChildren(int[] g, int[] s) {
 3        int count = 0;
 4        Arrays.sort(g);
 5        Arrays.sort(s);
 6        for (int i = s.length - 1; i >= 0; i--) {
 7            for (int j = g.length - 1; j >= 0; j--) {
 8                if (s[i] >= g[i]) {
 9                    count++;
10                    break;
11                }
12            }
13        }
14        return count;
15        // 计数器计数
16    }
17}
3.复杂度分析

时间复杂度:O(nlogn).数组排序的时间复杂度为O(nlogn),遍历数组的时间复杂度为O(n).
空间复杂度:O(n).创建count数值??

LeetCode:376. 摆动序列

376. 摆动序列 - 力扣(LeetCode)

1.思路

双指针法,求当前索引位置下的前后查值是否符合一正一负的条件,符合则count++,preDiff = curDiff

2.代码实现
 1class Solution {
 2    public int wiggleMaxLength(int[] nums) {
 3        if (nums.length <= 1) {
 4            return nums.length;
 5        }
 6        int curDiff = 0;
 7        int preDiff = 0;
 8        int count = 1;
 9        for (int i = 1; i < nums.length; i++) {
10            curDiff = nums[i] - nums[i - 1];
11            // 这里=只能给preDiff,curDiff上面被赋值之后,有可能会发生改变
12            if ((curDiff > 0 && preDiff <= 0) || (curDiff < 0 && preDiff >= 0)) { 
13                count++;
14                preDiff = curDiff;
15            }
16        }
17        return count;
18    }
19}
3.复杂度分析

时间复杂度:O(n).
空间复杂度:O(1).

LeetCode:53. 最大子序和

53. 最大子数组和 - 力扣(LeetCode)

1.思路

①两层for循环穷举所有子数组的和,比较得出最大值并返回即可

2.代码实现
 1// 暴力解法
 2class Solution {
 3    public int maxSubArray(int[] nums) {
 4        // 找到连续子数组,分别计算范围内的和,比较各个和
 5        int result = Integer.MIN_VALUE;
 6        for (int i = 0; i < nums.length; i++) {
 7            int curSum = 0;
 8            for (int j = i; j < nums.length; j++) {
 9                curSum += nums[j];
10                result = Math.max(result, curSum);
11            }
12        }
13        return result;
14    }
15}

// 时间复杂度:O(n^2)
// 空间复杂度:O(1)

 1// 贪心算法:剪枝操作
 2class Solution {
 3    public int maxSubArray(int[] nums) {
 4        int result = Integer.MIN_VALUE;
 5        int curSum = 0;
 6        for (int i = 0; i < nums.length; i++) {
 7            curSum += nums[i];
 8            result = Math.max(result, curSum);
 9            // 当前和为<= 0 时,剪枝操作
10            if (curSum <= 0) {
11                curSum = 0;
12            }
13        }
14        return result;
15    }
16}
3.复杂度分析

时间复杂度:O(n).
空间复杂度:O(1).

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值