MENU

LeetCode455. 分发饼干

July 5, 2018 • Read: 3105 • LeetCode阅读设置

贪心经典题,大意是说给你一个糖果大小的数组 s,给你孩子的需求数组 g,让你能尽可能多的满足孩子的需求,最多能满足多少个孩子

  • class Solution {
  • public int findContentChildren(int[] g, int[] s) {
  • int child = 0,cookie = 0;
  • Arrays.sort(g);
  • Arrays.sort(s);
  • while(child != g.length && cookie != s.length){
  • if(s[cookie] >= g[child]){
  • cookie++;
  • child++;
  • }
  • else
  • cookie++;
  • }
  • return child;
  • }
  • }
  • 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(s[cookie] >= g[child]){//糖果满足需求
  • cookie++;
  • child++;
  • }
  • else//不满足需求,糖果继续往后尝试
  • cookie++;
  • }
  • return child;
  • }
  • };
Last Modified: May 12, 2021
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment