原题链接:Leecode 455. 分发饼干
解法一:遍历数组
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
if(s.size()==0)
return 0;
sort(g.begin(),g.end());
sort(s.begin(),s.end());
int res=0,j=0;
for(int i=0;i<g.size();i++)
{
while(j<s.size() && s[j]<g[i])
j++;
if(j==s.size())
break;
if(s[j]>=g[i]) { res++; j++; }
}
return res;
}
};
解法二:双指针
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(),g.end());
sort(s.begin(),s.end());
int i=0,j=0;
while(i<g.size() && j<s.size())
{
if(g[i]<=s[j]) { i++;j++; }
else { j++; }
}
return i;
}
};