zoukankan      html  css  js  c++  java
  • Leetcode: 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 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: 1
    
    Explanation: 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: 2
    
    Explanation: 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<g.length && j<s.length; j++) {
     7             if (g[i] <= s[j]) i++;
     8         }
     9         return i;
    10     }
    11 }

    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<Integer, Integer> map = new TreeMap<Integer, Integer>();
     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 }
  • 相关阅读:
    谈谈ios内存管理--持续更新
    IOS整体框架介绍
    OC-精简解读 block
    解读自定义UICollectionViewLayout--感动了我自己
    内存管理-深浅拷贝之 copy和mutableCopy
    OC-socket使用介绍
    ios 调用系统打电话和发消息的功能
    Swift-扩展
    Java 之switch语句
    Java 键盘输入数据
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6168415.html
Copyright © 2011-2022 走看看