代码随想录刷题第31天

俗话说,年好过,月难熬。过年稍作休息5天,今天接着打代码。今天进入贪心算法章节。贪心算法的主要思想就是局部最优推出全局最优,与回溯算法不同的是,贪心并无什么固定的范式或策略,也就不存在所谓模版套路了。

第一题是分发饼干https://leetcode.cn/problems/assign-cookies/,局部最优是优先满足胃口大的孩子,先分发大饼干。

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
    sort(g.begin(), g.end());
    sort(s.begin(), s.end());
    int result = 0;
    int index = s.size() - 1;
    for (int i = g.size() - 1; i >= 0; i--){//遍历胃口
        if (index >= 0 && s[index] >= g[i]){
            index--;
            result++;
        }
    }
    return result;
    }
};

第二题是摆动序列https://leetcode.cn/problems/wiggle-subsequence/description/,删除单调过程中的点,保留峰值,确定摆动数量。

class Solution {
public:
    int wiggleMaxLength(vector<int>& nums) {
        if (nums.size() <= 1) return nums.size();
        int curDiff = 0;
        int preDiff = 0;
        int result = 1;
        for (int i = 0; i < nums.size() - 1; i++){
            curDiff = nums[i + 1] - nums[i];
            if ((preDiff <= 0 && curDiff > 0) || (preDiff >= 0 && curDiff < 0)){
                result++;
                preDiff = curDiff;
            }
        }
        return result;
    }
};

第三题是最大子序列和https://leetcode.cn/problems/maximum-subarray/description/,不难发现,当目前遍历的连续序列和小于0时,舍弃该序列。明确了思路,代码还是很简单的。

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
    int result = INT32_MIN;
    int count = 0;
    for(int i = 0; i < nums.size(); i++){
        count += nums[i];
        if (count > result) result = count;
        if (count < 0) count = 0;
    }
    return result;
    }
};

相关推荐

  1. 代码随想31

    2024-02-16 23:10:01       34 阅读
  2. 代码随想34

    2024-02-16 23:10:01       34 阅读
  3. 代码随想-五十六

    2024-02-16 23:10:01       40 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-16 23:10:01       17 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-16 23:10:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-16 23:10:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-16 23:10:01       18 阅读

热门阅读

  1. Python自动化应用:七个实用代码案例分享

    2024-02-16 23:10:01       25 阅读
  2. Redis-面试题

    2024-02-16 23:10:01       31 阅读
  3. 15.3 OpenGL可编程片段处理:片段着色器查询

    2024-02-16 23:10:01       34 阅读
  4. 「MySQL」事务

    2024-02-16 23:10:01       31 阅读
  5. 相向双指针题单

    2024-02-16 23:10:01       36 阅读
  6. leetcode刷题记录:二叉树02(思路篇)

    2024-02-16 23:10:01       32 阅读
  7. Spring基础 - Spring和Spring框架组成

    2024-02-16 23:10:01       28 阅读
  8. C++中const关键字详解

    2024-02-16 23:10:01       26 阅读
  9. C/C++中static关键字详解

    2024-02-16 23:10:01       30 阅读
  10. CCF编程能力等级认证GESP—C++1级—20231209

    2024-02-16 23:10:01       48 阅读