leetcode455.分发饼干、376. 摆动序列、53. 最大子序和

455.分发饼干

为了满足更多的小孩,就不要造成饼干尺寸的浪费

大尺寸的饼干既可以满足胃口大的孩子也可以满足胃口小的孩子,那么就应该优先满足胃口大的

这里的局部最优就是大饼干喂给胃口大的,充分利用饼干尺寸喂饱一个,全局最优就是喂饱尽可能多的小孩

可以尝试使用贪心策略,先将饼干数组和小孩数组排序。

然后从后向前遍历小孩数组,用大饼干优先满足胃口大的,并统计满足小孩数量

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());
        int index = s.size() - 1; // 饼干数组的下标
        int result = 0;
        for (int i = g.size() - 1; i >= 0; i--) { // 遍历胃口
            if (index >= 0 && s[index] >= g[i]) { // 遍历饼干
                result++;
                index--;
            }
        }
        return result;
    }
};
  • 时间复杂度:O(nlogn)
  • 空间复杂度:O(1)

376. 摆动序列

class Solution {
public:
    int wiggleMaxLength(vector<int>& nums) {
        int prediff = 0;
        int curdiff = 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)){
                prediff = curdiff;
                result++;
            }
        }
        return result;
    }
};
  1. 时间复杂度:O(n)
  2. 空间复杂度:O(n)

53. 最大子序和

注意两点:

  1. 什么时候选择起始位置?遇到负数就停止?还是和为负数就停止?
  • 遇到负数的时候不应该停止,因为后面可能有更大的正数可加
  • 当和为负数的时候就该停止了,因为这个负数只会拖累后面的数
  • 可以用result来记录最大值
  1. result的最小值应该初始化为什么?初始化为0吗?那如果数组中只有负数怎么办?
  • 因此,result应该初始化为无穷小
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int result = INT_MIN;
        int count = 0;
        for(int i = 0; i < nums.size(); i++){
            count += nums[i];
            result = count > result ? count : result;
            if(count < 0){
                count = 0;
            }
        }
        return result;
    }
};

最近更新

  1. Docker 容器出现 IP 冲突

    2024-06-06 02:54:05       0 阅读
  2. 构建安全稳定的应用:SpringSecurity实用指南

    2024-06-06 02:54:05       1 阅读
  3. 事务的范围比锁的范围大

    2024-06-06 02:54:05       1 阅读
  4. 深度解析:如何利用Python高效挖掘SQLite潜力

    2024-06-06 02:54:05       1 阅读
  5. C# 策略模式(Strategy Pattern)

    2024-06-06 02:54:05       1 阅读
  6. 【网络协议】PIM

    2024-06-06 02:54:05       1 阅读

热门阅读

  1. 在Go语言中如何使用变量

    2024-06-06 02:54:05       7 阅读
  2. 【4】MySQL数据库-备份

    2024-06-06 02:54:05       8 阅读
  3. Oracle大表在线重新分区

    2024-06-06 02:54:05       10 阅读
  4. linux各个日志的含义 以及使用方法

    2024-06-06 02:54:05       12 阅读
  5. 服务器硬件基础知识

    2024-06-06 02:54:05       8 阅读
  6. Linux文件系统杂记

    2024-06-06 02:54:05       8 阅读
  7. ORACLE RAC的一些基本理论知识

    2024-06-06 02:54:05       8 阅读
  8. oracle sys无法远程访问问题解决

    2024-06-06 02:54:05       10 阅读
  9. 程序员应该有什么职业素养?【模板】

    2024-06-06 02:54:05       9 阅读
  10. 查询DQL

    查询DQL

    2024-06-06 02:54:05      9 阅读