算法笔记|Day23贪心算法

发布于:2024-08-13 ⋅ 阅读:(103) ⋅ 点赞:(0)

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

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

题目分析

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

代码

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就行。

代码

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。

代码

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;
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到