LeetCode—455 分发饼干 Cpp&Python

LeetCode—455 分发饼干 Cpp&Python

假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。

输入: [1,2,3], [1,1]
输出: 1

因为有三个孩子,所提供尺寸只能满足胃口值为1的孩子,其余不满足,故输出1.

一、方法与思路

采用贪心算法的思想,即
优先满足胃口值小的,
且优先用小尺寸满足胃口值小的。
则大致思路如下:
先顺序排列胃口值g与尺寸值s,

从小到大开始遍历两个数组:

如果当前g[child]<=s[cookie],则可以满足该孩子的胃口,
否则,cookie++,看下一个饼干的大小能否满足对应孩子的胃口。

C++代码

#include <stdio.h>
#include <vector>
#include <algorithm>
class Solution {
public:
    int findContentChildren(std::vector<int>& g, std::vector<int>& s) {
    	std::sort(g.begin(), g.end());
    	std::sort(s.begin(), s.end());
    	int child = 0;
    	int cookie = 0;
    	while(child < g.size() && cookie < s.size()){
	    	if (g[child] <= s[cookie]){
	    		child++;
			}
			cookie++;
	    }
    	return child;
    }
};

int main(){
	Solution solve;
	std::vector<int> g;
	std::vector<int> s;
	g.push_back(5);
	g.push_back(10);
	g.push_back(2);
	g.push_back(9);
	g.push_back(15);
	g.push_back(9);
	s.push_back(6);
	s.push_back(1);
	s.push_back(20);
	s.push_back(3);
	s.push_back(8);	
	printf("%d\n", solve.findContentChildren(g, s));
	return 0;
}

Python代码

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g = sorted(g,reverse=True)
        s = sorted(s,reverse=True)
        child = cookie = 0
        while child != len(g) and cookie != len(s):
            if g[child] <= s[cookie]:
                j += 1
                child += 1
            cookie += 1
        return child

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值