leetcode 455. 分发饼干

这段代码是为LeetCode问题455. 分发饼干提供的两种解决方案。问题要求分配饼干给孩子,使尽可能多的孩子满足胃口。每个孩子都有一个胃口值,每个饼干都有一个尺寸值,饼干只能分给胃口值小于等于饼干尺寸的孩子。

方案1

cpp 复制代码
#include <vector>
#include <algorithm>
using std::vector;
/*
 * @lc app=leetcode.cn id=455 lang=cpp
 *
 * [455] 分发饼干
 */

// @lc code=start
class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        std::sort(g.begin(),g.end());
        std::sort(s.begin(),s.end());
        int m = g.size(); // 孩子的数量
        int n = s.size(); // 饼干的数量
        int count = 0;
        for (int i = 0, j = 0; i < m && j < n; i++, j++) {
            while (j < n && g[i] > s[j]) {
                j++;
            }
            if (j < n) {
                count++;
            }
        }
        return count;
    }
};
// @lc code=end

方案2

cpp 复制代码
#include <vector>
#include <algorithm>
using std::vector;
/*
 * @lc app=leetcode.cn id=455 lang=cpp
 *
 * [455] 分发饼干
 */

// @lc code=start
class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        std::sort(g.begin(), g.end());
        std::sort(s.begin(), s.end());
        int child = 0; // 能吃饱的孩子数量
        int cookie = 0;
        while (child < g.size() && cookie < s.size()) {
            if (g[child] <= s[cookie++]) {
                child++;
            }
        }
        return child;
    }
};
// @lc code=end

两种方案的解释和比较

方案1的解释
  1. 首先对孩子的胃口值数组 g 和饼干尺寸数组 s 进行排序。
  2. 使用两个指针 ij 分别遍历 gs
  3. 在每一步中,如果当前饼干的尺寸 s[j] 不满足当前孩子的胃口 g[i],则继续检查下一个饼干。
  4. 一旦找到满足当前孩子的饼干,就增加计数器 count,并移动到下一个孩子。
  5. 最后返回满足的孩子数量 count
方案2的解释
  1. 同样对孩子的胃口值数组 g 和饼干尺寸数组 s 进行排序。
  2. 使用两个指针 childcookie 分别遍历 gs
  3. 在每一步中,如果当前饼干 s[cookie] 可以满足当前孩子 g[child],则增加满足的孩子数量 child
  4. 无论是否满足当前孩子,饼干指针 cookie 都前进。
  5. 最后返回满足的孩子数量 child
比较
  • 方案1 使用了 while 循环内的 if 判断来跳过不满足的饼干,较为直观。
  • 方案2 代码更加简洁,使用 cookie++ 代替了 while 循环,使得每次都前进饼干指针,减少了循环的复杂度。

从效率上来看,两个方案的时间复杂度都是 O(n log n)(排序) + O(n)(遍历),但方案2的代码更简洁,易于理解和维护。

相关推荐
wenyq72 小时前
LeetCode 2460. Apply Operations to an Array
算法·leetcode
.格子衫.3 小时前
032动态规划之区间DP——算法备赛
算法·动态规划
青 春 记 忆3 小时前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表
不会代码的小猴3 小时前
7. JSON
开发语言·c++·笔记·qt·算法·json
怪奇云呼军4 小时前
知识库也会注入指令?闪电智能VoiceAgent 如何防住 Prompt Injection
人工智能·python·算法·云计算·音视频
阿里云大数据AI技术5 小时前
基于 EMR Serverless Ray 实现 Qwen 模型批量推理实践
人工智能·算法·agent
Rambo.xia5 小时前
为什么去马赛克算法,决定了ISP的画质上限
算法·接口隔离原则
Benny_Tang6 小时前
题解:P10230 [COCI 2023/2024 #4] Lepeze
c++·算法
Geek-Chow6 小时前
06 训练管线:数据如何变成权重
人工智能·算法