算法笔记|Day23贪心算法

算法笔记|Day23贪心算法

  • [☆☆☆☆☆leetcode 455.分发饼干](#☆☆☆☆☆leetcode 455.分发饼干)
  • [☆☆☆☆☆leetcode 376. 摆动序列](#☆☆☆☆☆leetcode 376. 摆动序列)
  • [☆☆☆☆☆leetcode 53. 最大子序和](#☆☆☆☆☆leetcode 53. 最大子序和)

☆☆☆☆☆leetcode 455.分发饼干

题目链接:leetcode 455.分发饼干

题目分析

优先考虑饼干,先喂饱小胃口:若饼干不足以喂孩子,则换下一块饼干;若能喂,则count加一,换下一块饼干喂下一个孩子。

代码

java 复制代码
class Solution {
    public int findContentChildren(int[] kid, int[] biscuit) {
        Arrays.sort(kid);
        Arrays.sort(biscuit);
        int count=0;
        int i=0;
        for(int j=0;i<kid.length&&j<biscuit.length;j++){
            if(biscuit[j]>=kid[i]){
                count++;
                i++;
            }
        }
        return count;
    }
}

☆☆☆☆☆leetcode 376. 摆动序列

题目链接:leetcode 376. 摆动序列

题目分析

此题需要计算前一个差值preDiff和当前差值curDiff,若一正一负(preDiff>0&&curDiff<0||preDiff<0&&curDiff>0)则出现摆动count加一。在此基础上,还应考虑以下三种情况:①上下坡中有平坡,需要在一侧补充等于0的情况,改为preDiff>=0和preDiff<=0;②数组首尾两端,考虑只有两个元素的情况,结果应为2,可以假设前一个preDiff为0,过程中加一,结尾自动加一,也就是count初始值为1,遍历是不考虑最后一个元素;③单调坡中有平坡只需要在这个坡度摆动变化的时候,更新preDiff就行。

代码

java 复制代码
class Solution {
    public int wiggleMaxLength(int[] nums) {
        int count=1;
        int preDiff=0,curDiff=0;
        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;
    }
}

☆☆☆☆☆leetcode 53. 最大子序和

题目链接:leetcode 53. 最大子序和

题目分析

依次遍历每个元素,并求得连续元素和,若比当前res值大,则赋给res。若当前连续元素和小于0,则重新计算元素和,sum赋值为0。

代码

java 复制代码
class Solution {
    public int maxSubArray(int[] nums) {
        int res=Integer.MIN_VALUE,sum=0;
        for(int i=0;i<nums.length;i++){
            sum+=nums[i];
            res=sum>res?sum:res;
            if(sum<0)
                sum=0;
        }
        return res;
    }
}
相关推荐
期末考复习中,蓝桥杯都没时间学了10 分钟前
力扣刷题19
算法·leetcode·职场和发展
日更嵌入式的打工仔16 分钟前
LAN9253中文注释第七章
笔记·原文翻译
Renhao-Wan18 分钟前
Java 算法实践(四):链表核心题型
java·数据结构·算法·链表
zmzb01031 小时前
C++课后习题训练记录Day105
开发语言·c++·算法
好学且牛逼的马2 小时前
【Hot100|25-LeetCode 142. 环形链表 II - 完整解法详解】
算法·leetcode·链表
H Corey2 小时前
数据结构与算法:高效编程的核心
java·开发语言·数据结构·算法
SmartBrain3 小时前
Python 特性(第一部分):知识点讲解(含示例)
开发语言·人工智能·python·算法
01二进制代码漫游日记3 小时前
自定义类型:联合和枚举(一)
c语言·开发语言·学习·算法
小学卷王3 小时前
复试day25
算法
样例过了就是过了3 小时前
LeetCode热题100 和为 K 的子数组
数据结构·算法·leetcode