C++ 贪心算法 分糖果

已知一些孩子和一些糖果,每个孩子有需求因子g,每个糖果有大小s,
当某个糖果的大小s>=某个孩子的需求因子g时,代表该糖果可以满足孩子;求使用这些糖果,最多能满足多少孩子?
(某个孩子只能用1个糖果满足)
例如:需求因子组g=[5,10,2,9,15,9];糖果大小数组s=[6,1,20,3,8];最多可以满足3个孩子。

#include<vector>
#include<algorithm>
class Solution
{
public:
 Solution(){}
 ~Solution(){}
 int findContentChildren(std::vector<int>& g, std::vector<int>& s)
 {
  std::sort(g.begin(), g.end());
  std::sort(s.begin(), s. end());
  unsigned int child = 0;
  unsigned int cookie = 0;
  while (child<g.size() && cookie<s.size())
  {
   if (g[child] <= s[cookie])
   {
    child++;
   }
   cookie++;
  }
  return child;
 }
};
int main()
{
 Solution solve;
 std::vector<int> g;
 std::vector<int> s;
 g.push_back(5);
 g.push_back(10);
 g.push_back(2);
 g.push_back(9);
 g.push_back(15);
 g.push_back(9);
 s.push_back(6);
 s.push_back(1);
 s.push_back(20);
 s.push_back(3);
 s.push_back(8);
 printf("%d\n",solve.findContentChildren(g,s));
 return 0;
}

运行结果:
3

发布了31 篇原创文章 · 获赞 1 · 访问量 680

猜你喜欢

转载自blog.csdn.net/weixin_44208324/article/details/104559299