代码随想录训练营第三十二天|贪心算法

本来这是第三十一天的内容,但是三十一天的时候写成第三十二天的了,因此今天写第三十一天的内容

 

455.分发饼干 

复制代码
class Solution {
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int n = g.length;
        int m = s.length;
        if(m==0||n==0){
            return 0;
        }
        int res = 0;
        int j = 0;
        for(int i = 0; i<n; i++){
            if(j>m-1){
                return res;
            }
            while(g[i]>s[j]){
                j++;
                if(j>m-1){
                   return res;
            }
               
           }
            j++;
            res++;
        }
        return res;
    }
}
复制代码

进行排序,然后再对比,试图让最小的size符合最小人的胃口

  

376. 摆动序列 

复制代码
class Solution {
    public int wiggleMaxLength(int[] nums) {
        int n = nums.length;
        if (n == 1){
            return n;
        }
        int cur = 0;
        int pre = 0;
        
        int res = 1;
        for(int i = 1; i< n; i++){
            cur = nums[i] - nums[i-1];
            
            if(cur>0&&pre<=0 || cur < 0 && pre >= 0){
                res++;
                pre = cur;
            }
        }
        return res;
    }
}
复制代码

如果有正负转换的变动,那么就计数+1;

53. 最大子序和 

复制代码
class Solution {
    public int maxSubArray(int[] nums) {
        int n = nums.length;
        if(n==1){
            return nums[0];
        }
        int res = nums[0];


        int sum  = nums[0];
        for(int i = 1; i<n; i++){
            if(sum >= 0){
                sum += nums[i];
            }
            else{
                sum = nums[i];
            }
            res = Math.max(res, sum);
        }
        return res;



    }
}
复制代码

不断往前,如果结果为负数就舍弃这段结果,重新开始

 

贪心算法只有思路没有模版

posted @   小猫Soda  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示