LeetCode 455 分发饼干 - 贪心解法

LeetCode 455 分发饼干 - 贪心解法

https://leetcode.cn/problems/assign-cookies/description/

思路

核心贪心:每次优先满足当前胃口最小的孩子。

双指针法
孩子没被满足时,饼干后移;中间无法满足当前孩子的饼干直接跳过。
while(){
	if(满足){
		孩子后移
	}
	饼干后移
}

代码

class Solution {

public:

    int findContentChildren(vector<int>& g, vector<int>& s) {

        sort(g.begin(), g.end());

        sort(s.begin(), s.end());

        int i = 0; // 孩子指针

        int j = 0; // 饼干指针

        while (i < g.size() && j < s.size()) {

            if(s[j]>=g[i]){

                i++;

            }

            j++;

        }

        return i; // 满足的孩子数量

    }

};