【贪心】C_009 分发饼干(暴力 | 双指针)

一、题目描述

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.
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.

二、题解

方法一:排序

  • 显然最优策略是每次尝试将尺寸 size 最小的饼干先发出去。
  • 注意,发出去的饼干是不能在分配的了,所以这里用了一个 boolean[] vis 数组记录已分发的饼干。
public int findContentChildren(int[] g, int[] s) {
    Arrays.sort(g);
    Arrays.sort(s);
    int count = 0;
    boolean[] vis = new boolean[s.length];
    
    for (int i = 0; i < g.length; i++)
    for (int j = 0; j < s.length; j++) {
        if (s[j] >= g[i] && !vis[j]) {
            count++;
            vis[j] = true;
            break;
        }
    }
    return count;
}

复杂度分析

  • 时间复杂度: O ( n × m ) O(n × m) O(n×m),这样做很容易想到,但是效率略低。
  • 空间复杂度: O ( m ) O(m) O(m)

方法二:双指针

  • 排完序之后,如果 s[cookie] 满足不了 g[child]cookie 自然也就需要向后移动,寻找更大的饼干了。
  • 如果 s[cookie] 可满足 g[child],那么尝试满足下一个孩子即可。
public int findContentChildren(int[] g, int[] s) {
    Arrays.sort(g);
    Arrays.sort(s);
    int child = 0, cookie = 0;

    while (child < g.length && cookie < s.length) {
        if (g[child] <= s[cookie]) {
            child++;
        }
        cookie++;
    }    
    return child;
}

复杂度分析

  • 时间复杂度: O ( n l o g n ) O(nlogn) O(nlogn),n 为孩子与饼干数量的最大者.
  • 空间复杂度: O ( 1 ) O(1) O(1)

你可能感兴趣的:(#,【贪心】)