题目来源
分糖果的问题,我想到的是先把孩子和糖果排序,然后从后往前遍历,假如糖果大于孩子,就给。
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
auto n1 = g.size();
auto n2 = s.size();
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int p1 = n1 - 1, p2 = n2 - 1;
int cnt = 0;
while (p2 >= 0 && p1 >= 0) {
if (s[p2] >= g[p1]) {
cnt++;
p2--;
}
p1--;
}
return cnt;
}
};
然后看了下讨论区,其实从前往后更简单一些,假如糖果满足孩子,就给。其实都一样,只是代码写的简单了一些。
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
auto n1 = g.size();
auto n2 = s.size();
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int i = 0;
for (int j=0; i<n1 && j<n2; j++)
if (s[j] >= g[i])
i++;
return i;
}
};