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 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,2],[2,1],那么可能出现给胃口1分配了饼干2,导致最后只能满足一个胃口的情况。

class Solution {
    public int findContentChildren(int[] g, int[] s) {
      int result=0;
        int cookies=0;
         Arrays.sort(g);
        Arrays.sort(s);
        for (int i = 0; i < s.length; i++) {
            for (int j = cookies; j < g.length; j++) {
                if(g[j]==-1) continue;
                if(g[j]<=s[i]){
                    result++;
                    cookies++;
                    g[j]=-1;
                    break;
                }
            }
        }
        return result;
    }
}

该解法性能如下:

执行用时 : 66 ms, 在所有 Java 提交中击败了8.61%的用户
内存消耗 :39.5 MB, 在所有 Java 提交中击败了95.97%的用户

解法二

这个解法其实是对解法一的优化。因为解法一中,我们看到能够满足的孩子数不会超过g.length。所有能分配的饼干数不会超过s.length。优化后的代码如下:

class Solution {
    public int findContentChildren(int[] g, int[] s) {
        int count=0,child=0,cookie=0;
        Arrays.sort(g);
        Arrays.sort(s);
        while(child<g.length && cookie<s.length){
            if(g[child]<=s[cookie]){
                count++;
                child++;
            }  
                cookie++;     
        }
        return count;
    }
}

该解法性能如下:

执行用时 : 10 ms, 在所有 Java 提交中击败了99.39%的用户
内存消耗 :39.1 MB, 在所有 Java 提交中击败了96.30%的用户

posted @ 2019-10-21 14:38  六层楼  阅读(158)  评论(0编辑  收藏  举报