2020-12-25今日份力扣==455. 分发饼干

来源:链接:https://leetcode-cn.com/problems/assign-cookies
声明:如果我侵犯了任何人的权利,请联系我,我会删除
欢迎高手来喷我

题目

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

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

示例 1:
输入: g = [1,2,3], s = [1,1]
输出: 1
解释:
你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。
所以你应该输出1。

示例 2:
输入: g = [1,2], s = [1,2,3]
输出: 2
解释:
你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。
你拥有的饼干数量和尺寸都足以让所有孩子满足。
所以你应该输出2.

提示:
1 <= g.length <= 3 * 10^4
0 <= s.length <= 3 * 10^4
1 <= g[i], s[j] <= 2^31 - 1

我的代码 双指针

这里就是先对两个数组排序,两个指针指向数组的开头,一个一个的比较

  • g[i] <= s[j] 说明糖果可以分给g[i],ret++;
  • g[i] > s[j] 说明糖果不可以分给个g[i], [j++]指向下一个糖果
class Solution {
    public int findContentChildren(int[] g, int[] s) {
        //Arrays.sort(g);
        quickSort(g, 0, g.length-1);
        quickSort(s, 0, s.length-1);
        //Arrays.sort(s);
        int i=0, j=0;

        int ret=0;
        while(i<g.length && j<s.length){
            if(g[i] <= s[j]){
                ret++;
                i++; j++;
            }else{
                j++;
            }
        }
        return ret;
    }
    public void quickSort(int[] arr, int start, int end){
        if(start >= end) return;
        int p = partition(arr, start, end);
        quickSort(arr, start, p);
        quickSort(arr, p+1, end);
    }
    public int partition(int[]arr, int left, int right){
        int key = arr[left]; 
        while(left < right){
            while(left < right && arr[right] >= key) right--;
            arr[left] = arr[right];
            while(left < right && arr[left] <= key) left ++;
            arr[right] = arr[left]; 
        }
        arr[left] = key;
        return left;
    }
}
大神的代码

都是这个思路,
https://leetcode-cn.com/problems/assign-cookies/solution/fen-fa-bing-gan-by-leetcode-solution-50se/

class Solution {
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int numOfChildren = g.length, numOfCookies = s.length;
        int count = 0;
        for (int i = 0, j = 0; i < numOfChildren && j < numOfCookies; i++, j++) {
            while (j < numOfCookies && g[i] > s[j]) {
                j++;
            }
            if (j < numOfCookies) {
                count++;
            }
        }
        return count;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/assign-cookies/solution/fen-fa-bing-gan-by-leetcode-solution-50se/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自blog.csdn.net/qq_45531729/article/details/111674079