每日刷题:455.分发饼干

218 阅读1分钟

455.分发饼干(难度:简单)

假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。

对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。

解题思路

为了有限满足低饱腹感的孩子,以及优先消耗小饼干,将先对孩子的饱腹感以及饼干的尺寸进行排序,再进行计算。

题解

public int findContentChildren(int[] children, int[] cookies) {
    Arrays.sort(children);
    Arrays.sort(cookies);
    int child = 0;
    int cookie = 0;
    while(child < children.length && cookie < cookies.length) {
        if(children[child] <= cookies[cookie]) {
            ++child;
        }
        ++cookie;
    }
    return child;
}

测试

AssignCookies assignCookies = new AssignCookies();

private void test_findContentChildren(int[] children, int[] cookies, int expected) {
    int childCount = assignCookies.findContentChildren(children, cookies);
    Assertions.assertEquals(expected, childCount);
}

@Test
public void text_case1() {
    test_findContentChildren(new int[]{1, 2, 3}, new int[]{1, 1}, 1);
}

@Test
public void test_case2() {
    test_findContentChildren(new int[]{1, 2}, new int[]{1, 2, 3}, 2);
}