leetcode 455: Assign Cookies

问题描述:
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

分析:题目很简单,说有大小不一的一些饼干,还有饥饿程度不同的孩子。我们需要把饼干分配给孩子,要求饼干大小>=孩子的需求,且一个孩子只能得到一块饼干。求出最多能分配多少饼干(亦即能让多少孩子吃饱)

思路:典型的贪心算法。我们先排序,再分配。分配时我们从需求最小的孩子开始,给予能满足他的最小块的饼干。如果最小的饼干可以满足需求最小的孩子,则我们排除这个孩子和这块饼干并增加一个记录;否则,我们要尝试用更大一点的饼干给这个孩子。循环直到饼干没了或孩子都拿到饼干了。

代码如下:

class Solution {
    public int findContentChildren(int[] g, int[] s) {
        //sort the two arrays
        Arrays.sort(g);
        Arrays.sort(s);
        int i=0;
        int j=0;
        int counter=0;
        //loop if we have cookies and hungry children
        while((i<=g.length-1)&&(j<=s.length-1)){
            //if we can feed the least greedy child with the smallest cookie
            if(s[j]>=g[i]){
                i++;
                j++;
                counter++;
            }
            //otherwise, we try to feed the least greedy child with a bigger cookie
            else{
                j++;
            }
        }
        return counter;
    }
}

时间复杂度: O(nlogn), 受制于排序算法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值