博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Assign Cookies
阅读量:5056 次
发布时间:2019-06-12

本文共 2171 字,大约阅读时间需要 7 分钟。

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 gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, 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.Note:You may assume the greed factor is always positive. You cannot assign more than one cookie to one child.Example 1:Input: [1,2,3], [1,1]Output: 1Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.You need to output 1.Example 2:Input: [1,2], [1,2,3]Output: 2Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2.

Solution 1: Greedy, Time:O(nlogn)

Just assign the cookies starting from the child with less greediness to maximize the number of happy children .

1 public class Solution { 2     public int findContentChildren(int[] g, int[] s) { 3         Arrays.sort(g); 4         Arrays.sort(s); 5         int i = 0; 6         for (int j=0; i

 

Solution 2: Greedy + TreeMap,   Time: O(nlogm), n, m are the size of two arrays respectively

1 public class Solution { 2     public int findContentChildren(int[] g, int[] s) { 3         TreeMap
map = new TreeMap
(); 4 int res = 0; 5 for (int size : s) { 6 map.put(size, map.getOrDefault(size, 0)+1); 7 } 8 9 for (int greed : g) {10 if (map.ceilingKey(greed) != null) {11 res++;12 int value = map.ceilingKey(greed);13 map.put(value, map.get(value)-1);14 if (map.get(value) == 0) map.remove(value);15 }16 }17 return res;18 }19 }

 

转载于:https://www.cnblogs.com/EdwardLiu/p/6168415.html

你可能感兴趣的文章
一步步学习微软InfoPath2010和SP2010--第七章节--从SP列表和业务数据连接接收数据(4)--外部项目选取器和业务数据连接...
查看>>
如何增强你的SharePoint 团队网站首页
查看>>
FZU 1914 Funny Positive Sequence(线性算法)
查看>>
oracle 报错ORA-12514: TNS:listener does not currently know of service requested in connec
查看>>
基于grunt构建的前端集成开发环境
查看>>
MySQL服务读取参数文件my.cnf的规律研究探索
查看>>
java string(转)
查看>>
__all__有趣的属性
查看>>
BZOJ 5180 [Baltic2016]Cities(斯坦纳树)
查看>>
写博客
查看>>
利用循环播放dataurl的视频来防止锁屏:NoSleep.js
查看>>
python3 生成器与迭代器
查看>>
java编写提升性能的代码
查看>>
ios封装静态库技巧两则
查看>>
Educational Codeforces Round 46 (Rated for Div. 2)
查看>>
Abstract Factory Pattern
查看>>
Cocos2d-x 3.0final 终结者系列教程10-画图节点Node中的Action
查看>>
简单理解kafka---核心概念
查看>>
assert用法
查看>>
ajaxFileUpload.js 上传后返回的数据不正确 -- clwu
查看>>