算法笔记|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;
    }
}
相关推荐
思成不止于此3 小时前
MySQL 查询实战(三):排序与综合练习
数据库·笔记·学习·mysql
Savior`L4 小时前
二分算法及常见用法
数据结构·c++·算法
深海潜水员4 小时前
OpenGL 学习笔记 第一章:绘制一个窗口
c++·笔记·学习·图形渲染·opengl
摇滚侠5 小时前
ElasticSearch 教程入门到精通,文档创建查询修改删除,笔记10、11、12
笔记·elasticsearch
mmz12075 小时前
前缀和问题(c++)
c++·算法·图论
努力学算法的蒟蒻5 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
崇山峻岭之间5 小时前
C++ Prime Plus 学习笔记026
c++·笔记·学习
甄心爱学习6 小时前
CSP认证 备考(python)
数据结构·python·算法·动态规划
kyle~6 小时前
排序---常用排序算法汇总
数据结构·算法·排序算法