Loading

LeetCode 455. 分发饼干

 

思路

贪心思想,先对小孩的胃口和饼干的尺寸进行从小到大排序,每次选出能满足该小孩的最小饼干。
 1 class Solution {
 2 public:
 3     int findContentChildren(vector<int>& g, vector<int>& s) {
 4         // 先对小孩和饼干从小到大排序
 5         sort(g.begin(), g.end());
 6         sort(s.begin(), s.end());
 7 
 8         // res保存结果
 9         int res = 0;
10         // i遍历小孩,j遍历饼干
11         int i = 0, j = 0;
12         // 每次选出能满足该小孩的最小饼干
13         while(i < g.size() && j < s.size()) {
14             if(s[j] >= g[i]) {
15                 i++;
16                 j++;
17                 res++;
18             } else {
19                 j++;
20             }
21         }
22 
23         return res;
24     }
25 };

 

posted @ 2020-11-05 08:44  拾月凄辰  阅读(72)  评论(0编辑  收藏  举报