题目分析:先将孩子的胃口和饼干的大小从小到大排序,然后从胃口小的孩子发饼干,遍历饼干的大小,分给所能满足当前孩子的最小的饼干.这里先用了2个sort函数排序,不知道有没有不需要排序的算法
C++:
int findContentChildren(vector<int>& g, vector<int>& s) {
int count = 0;
int i = 0 , j = 0;
int len_g = g.size();
int len_s = s.size();
sort(g.begin() , g.end());
sort(s.begin() , s.end());
while (i<len_g && j<len_s){
if (g[i] <= s[j]){
i ++;
j ++;
count ++;
} else{
j ++;
}
}
return count;
}
Python:
def findContentChildren(g: List[int], s: List[int]) -> int:
count = 0
i = 0
j = 0
len_g = len(g)
len_s = len(s)
g.sort()
s.sort()
while i < len_g and j < len_s:
if g[i] <= s[j]:
i += 1
j += 1
count += 1
else:
j += 1
return count