贪心算法之Assign Cookie-leetcode

腾讯云智后台开发实习面试全纪录(已offer) 腾讯云智后台开发实习面经 阅读详情

1. 问题描述

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

Note:
You may assume the greed factor is always positive.
You cannot assign more than one cookie to one child.

2. 详细讲解

  1. 本题是对应于贪心算法的习题,我们来复习(预习)一波贪心算法

    • 贪心算法(又称贪婪算法)是指,在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,他所做出的是在某种意义上的局部最优解。

    • 贪心算法不是对所有问题都能得到整体最优解,关键是贪心策略的选择,选择的贪心策略必须具备无后效性,即某个状态以前的过程不会影响以后的状态,只与当前状态有关。

    • 贪心算法在有最优子结构的问题中尤为有效。最优子结构的意思是局部最优解能决定全局最优解。简单地说,问题能够分解成子问题来解决,子问题的最优解能递推到最终问题的最优解

贪心算法与动态规划的不同在于它对每个子问题的解决方案都做出选择,不能回退。动态规划则会保存以前的运算结果,并根据以前的结果对当前进行选择,有回退功能。

常用于,背包问题,最小生成树,哈夫曼编码。

1.建立数学模型来描述问题。
2.把求解的问题分成若干个子问题。
3.对每一子问题求解,得到子问题的局部最优解。
4.把子问题的解局部最优解合成原来解问题的一个解。

实现该算法的过程:
从问题的某一初始解出发;while 能朝给定总目标前进一步 do ,求出可行解的一个解元素;
最后,由所有解元素组合成问题的一个可行解。


2.贪心策略适用的前提是:局部最优策略能导致产生全局最优解。
(point)实际上,贪心算法适用的情况很少。一般,对一个问题分析是否适用于贪心算法,可以先选择该问题下的几个实际数据进行分析,就可做出判断

3. 代码

尽量给每个人能接受的最小的蛋糕就好,直接排序后,两个数组从头开始就好

public class Solution {

    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int res = 0;
        int i = 0;
        int j = 0;
        while( i < g.length && j < s.length){
            if( g[i]<=s[j] ){
                i++;
                j++;
                res++;
            } else{
                j++;
            }
        }
        return res;

    }
}
ESP32开发板使用Arduino实现变成蓝牙鼠标教程 通过这个教程,你可以轻松将ESP32开发板变成蓝牙鼠标。如果你在使用过程中遇到任何问题,或者库没有正常工作,不妨下载我上传的修复版本,再试试看。希望你们能根据这个基础做出更多有趣的蓝牙控制项目! 阅读详情

相关推荐

从噪声中提取真相:LabVIEW振动信号积分处理的降噪艺术

本文深入探讨了LabVIEW在振动信号积分处理中的降噪技术,揭示了如何通过选择性频率加权从噪声中提取关键故障特征。详细介绍了时域和频域积分方法的实现原理及优化策略,并结合工业案例展示了多轴信号联合降噪的实际应用效果,为设备状态监测提供了高效解决方案。

weixin_29164185的博客 302

455. Assign Cookies

455. Assign Cookies

相信相信的力量 614

XGBoost详解(原理篇)

XGBoost全称为eXtreme Gradient Boosting,即极致梯度提升树。XGBoost是Boosting算法的其中一种,Boosting算法的思想是将许多弱分类器集成在一起,形成一个强分类器(个体学习器间存在强依赖关系,必须串行生成的序列化方法)。Note:关于Boosting算法详见博文集成学习详解_tt丫的博客-优快云博客XGBoost是一种提升树模型,即它将许多树模型集成在一起,形成一个很强的分类器。其中所用到的树模型则是CART回归树模型。

tt丫的博客 7万+

assign-cookies(贪心算法)

assign-cookies 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。 注意: ...

qq_36653524的博客 486

我从华为身上学到的项目管理经验 -- 需求篇

记录这三年,关于项目管理上的一些心得体会 – 需求篇对于需求,我们可以根据不同的角色、理解拆分成三个过程:简单来说就是:需求分析原始需求、 需求拆分为系统需求、 需求实现为功能需求**需求分析**: 将客户需求 输出成 需求描述。 需求经理需要把 需求 转换成 客户能够接受的 初始需求 IR(Initial Requirement) 对于用户来说,我只管提 我的原始需求是

minminzhe520的博客 3万+

基于Simulink的轨道交通信号控制系统仿真详细介绍

轨道交通信号控制系统是确保列车安全、高效运行的核心技术。通过Simulink进行信号控制系统的仿真,可以验证系统的设计、优化调度策略并提高安全性。以下是如何在MATLAB和Simulink中设计并仿真一个轨道交通信号控制系统的详细步骤。通过上述步骤,我们成功设计并实现了基于Simulink的轨道交通信号控制系统仿真。该系统能够根据列车位置、速度和轨道状态生成控制指令,确保列车的安全、高效运行。通过虚拟场景仿真、硬件在环测试和实机测试,验证了系统的性能,并通过参数优化进一步提升了系统的可靠性。引入智能调度。

xiaoheshang_123的博客 462

Assign Cookies

#include<vector> #include<algorithm> class Solution { public: int find(std::vector<int>& q, std::vector<int>& s) //这里的& 是引用的意思 { std::sort(q.begin(), q.end()); ...

weixin_43983814的博客 197

MicroCap声学仿真介绍(一)

5-频率上下限选择,需要注意的是,第一个数字是上限,第二个数字是下限,如果填反了,会有报错提示;下三角可以选择“Auto”、“linear”、“log”和“list”,设置的是频率点之间的距离和频率点的数量。Component是用来选择部件的模块,如上图所示,声学仿真常用到的是“Electroacoustic Macros AC”、“Electroacoustic Macros TR”、“NXP Transducers”以及“NXP HD components”。3是声学部件,是声学仿真中常用的部件。

山无忧的博客 5089

455. Assign Cookies -- 贪心算法

455. Assign Cookies – 贪心算法Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is

BLUE BOX 436

计算机组成原理(第三版)唐朔飞-第七章指令系统-课后习题

机器字长是指CPU一次能处理数据的位数通常与CPU的寄存器位数有关。指令字长是指机器指令中二进制代码的总位数。存储字长是指存储单元中存放二进制代码的总位数。三者可以相等也可以不等视不同机器而定。答:OP(4位)A1(6位)A_1(6位)A1​(6位)A2(6位)A_2(6位)A2​(6位)设二地址指令格式为该指令系统的基本格式,4位操作码共有16种编码,其中13种用来定义二地址指令,还剩3种可用作扩展标志。一地址指令条数=3∗26=192。

weixin_45735391的博客 7万+

Mastercam软件二次开发:使用C#进行Mastercam二次开发

C#(发音为“C Sharp”)是一种现代、面向对象的编程语言,由微软开发,首次发布于2000年。它结合了C和C++的强大功能,同时引入了Java的垃圾回收机制,使得C#在开发效率和运行性能之间找到了一个良好的平衡点。C#的设计目标是提高开发者的生产力,它支持多种编程范式,包括面向对象、泛型、委托和事件等,这使得它成为开发Windows应用程序、Web应用程序、游戏(尤其是使用Unity引擎)和企业级应用的理想选择。

kkchenjj的博客 2213

LeetCode刷题笔记(Assign Cookies)

从今天开始就进入了贪心算法的板块了,感觉贪心算法思考起来比动态规划要简单一些,下面就和大家分享一下刚刷的这道题。 题目如下: 题意分析: 给定一些大小尺寸不同的 cookie 和一群贪心指数不同的小朋友,当小朋友获得了 cookie 的大小不小于自己贪心指数时,小孩将会变得很开心,请问给定的 cookie 最多能让几个小朋友开心? 方法一(贪婪算法) 先对 g、s 两个数组按照从大到...

Vensmallzeng的博客 827

红火蚁巢穴AI智能识别,提供方案与思路!

🏆本文收录于 《全栈 Bug 调优(实战版)》 专栏。专栏聚焦真实项目中的各类疑难 Bug,从成因剖析 → 排查路径 → 解决方案 → 预防优化全链路拆解,形成一套可复用、可沉淀的实战知识体系。无论你是初入职场的开发者,还是负责复杂项目的资深工程师,都可以在这里构建一套属于自己的「问题诊断与性能调优」方法论,助你稳步进阶、放大技术价值 。

**My Coding Family** 1041

leetcode_assign-cookies

题目链接 https://leetcode-cn.com/problems/assign-cookies/ 题目内容 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。 对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。 示例 1 输入: g

weixin_38554391的博客 169

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LeetCode -- Assign Cookies

LeetCode -- Assign Cookies

我的英文站点:https://iorilan.medium.com/ 674

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

贪心法——LeetCode Assign Cookies分饼干

贪心法 遵循某种规律,不断贪心的选取当前最优策略的算法设计方法 题目:LeedCode 455.Assign Cookies 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。 你可以假设胃口值为

gl620321的博客 357

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

[LeetCode] 455. Assign Cookies

题目内容 https://leetcode-cn.com/problems/assign-cookies/ 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj。如果 sj>= gi,我们可以将这个饼干 j 分配给孩子 i ,这个...

Reyiiiin的深夜一点半 110

LeetCode455Assign Cookies

问题描述: Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum

u010499172的专栏 264

【力扣算法LeetCode】455 Assign Cookies分发饼干

文章目录前言一、题目二、解答1.代码2.复盘总结 前言 题目出自力扣 算法练习题: 一、题目 题目 题目链接 测试用例 二、解答 1.代码 代码如下(示例): 2.复盘 总结

南迁的博客 195

leetcode assign-cookies

455.Assign Cookies Easy 26957FavoriteShare Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child...

dibanfu3470的博客 157

[LeetCode] Assign Cookies 分饼干

声明:原题目转载自LeetCode,解答部分为原创 Problem: Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a gree

xblog_的博客 347

leetCode---Assign Cookies

一. 题目:Remove Duplicates from Sorted Array II        Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? 二. 思路分析     因为题目是所给数组已经排序的数组,所以加一个变量记录一下元素出现的次数,这样加一个变量即可解决

jingxichen_的专栏 202

LeetCode - Assign Cookies

25.07.2021 小白一枚,文章仅当日记本记录学习进度 ;) 如被浏览,请多多指教,非常感谢大家纠错与建议! (因留学顺便练习英语,所以部分用英文笔记,并无他意) class Solution { public int findContentChildren(int[] g, int[] s) { Arrays.sort(g); Arrays.sort(s); int child = 0, cookie = 0; w.

weixin_45566492的博客 140

leetcode 455. Assign Cookies

考察的是贪心算法,总体而言是满足局部条件,从而解决整体问题。 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。 对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。 示例1. 输入: g = [1,2,3], s = [1,1] 输出: 1

weixin_37779156的博客 210

Leetcode - 455. Assign Cookies (贪心算法)

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a coo...

BUPT-WT的博客 148

LeetCode : 455. Assign Cookies 分饼干

试题: Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a...

心之所向 239
上一篇: LeetCode-Majority Element
下一篇: 动态规划--LIS与LCS
Coder_zyq
博客等级 码龄10年 3粉丝 23原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值