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的代码更简洁,易于理解和维护。

相关推荐
爱学习的张大3 分钟前
具身智能论文精读(五):OpenVLA
人工智能·算法
逻辑驱动的ken40 分钟前
Java高频面试场景题19
java·开发语言·面试·职场和发展·求职招聘
刘大猫.1 小时前
宝马发布全新AI智能座舱助手 能理解用户复杂出行需求
人工智能·算法·机器学习·ai·大模型·算力·ai智能座舱助手
如何原谅奋力过但无声1 小时前
【灵神高频面试题合集01-03】相向双指针、滑动窗口
数据结构·python·算法·leetcode
leoufung1 小时前
LeetCode 42:接雨水 —— 从“矩形法”到双指针的完整思考过程
java·算法·leetcode
_日拱一卒2 小时前
LeetCode:543二叉树的直径
算法·leetcode·职场和发展
汉克老师2 小时前
GESP2025年3月认证C++五级( 第一部分选择题(9-15))
c++·算法·高精度计算·二分算法·gesp5级·gesp五级
穿条秋裤到处跑3 小时前
每日一道leetcode(2026.04.28):获取单值网格的最小操作数
算法·leetcode·职场和发展
leoufung3 小时前
LeetCode 68. Text Justification 题解:贪心与实现细节
算法·leetcode·职场和发展
WL_Aurora3 小时前
【每日一题】前缀和
python·算法