【贪心算法1】

力扣455.分发饼干

链接: link

思路

尽可能让更多人吃到饼干并且尽可能少的造成浪费,大尺寸饼干能满足大胃口的人就应该优先分给大胃口的人。所以先将饼干和胃口大小排序,然后从后往前遍历。但是这时候又有一个问题,饼干和胃口哪个作为for循环哪个作为if呢?答案是只能胃口作为for,饼干作为if,因为for循环的i是固定每次移动,而饼干index只有满足条件才会移动。这里可以举一个反例,如果最大胃口大于最大的饼干,以饼干为for循环,胃口为if,那么for循环遍历下来,所有人都分不到饼干。

方法1:

javascript 复制代码
class Solution {
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int index = s.length - 1;
        int cnt = 0;
        // 遍历胃口
        for(int i = g.length - 1;i>=0;i--){
            if(index>=0&&s[index]>=g[i]){
                cnt++;
                index--;
            }
        }
        return cnt;
    }
}

376.摆动序列

链接: link

思路

这道题看起代码简单,但是要考虑的情况很多,直接参考链接内容吧

javascript 复制代码
class Solution {
    public int wiggleMaxLength(int[] nums) {
        if (nums.length <= 1) {
            return nums.length;
        }
        // 当前节点 - 前一个节点
        int pre = 0;
        // 后一个节点 - 当前节点
        int next = 0;
        int res = 1;
        for (int i = 0; i < nums.length - 1; i++) {
            next = nums[i + 1] - nums[i];
            // 出现峰值
            if ((pre >= 0 && next < 0) || (pre <= 0 && next > 0)) {
                res++;
                pre = next;
            }
        }
        return res;
    }
}

53.最大子数组和

链接: link

javascript 复制代码
class Solution {
    public int maxSubArray(int[] nums) {
        if(nums.length == 1){
            return nums[0];
        }
        int sum = Integer.MIN_VALUE;
        int cnt = 0;
        for(int i = 0;i<nums.length;i++){
            cnt += nums[i];
            if(cnt>=sum){
                sum = cnt;
            }
            if(cnt<0){ // 注意 只有区间和为负数时才会重置
                cnt = 0;
            }
        }
        return sum;
    }
}
相关推荐
历程里程碑11 小时前
Linux22 文件系统
linux·运维·c语言·开发语言·数据结构·c++·算法
你撅嘴真丑18 小时前
第九章-数字三角形
算法
uesowys18 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
ValhallaCoder19 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮19 小时前
AI 视觉连载1:像素
算法
智驱力人工智能19 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
孞㐑¥20 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
月挽清风20 小时前
代码随想录第十五天
数据结构·算法·leetcode
XX風20 小时前
8.1 PFH&&FPFH
图像处理·算法
NEXT0620 小时前
前端算法:从 O(n²) 到 O(n),列表转树的极致优化
前端·数据结构·算法