
题目:
假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
注意:
你可以假设胃口值为正。
一个小朋友最多只能拥有一块饼干。
示例 1:
输入: [1,2,3], [1,1]
输出: 1
解释:
你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。
所以你应该输出1。
示例 2:
输入: [1,2], [1,2,3]
输出: 2
解释:
你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。
你拥有的饼干数量和尺寸都足以让所有孩子满足。
所以你应该输出2.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/assign-cookies
思路:
用优先队列分别存储孩子的胃口和饼干的尺寸,优先队列按从小到大排列,每弹出一个饼干尺寸就与此时孩子队列顶部的胃口作比较,如果符合就弹出两个队列的顶部,不符合只弹出饼干队列的顶部,直到其中一个队列为空。
代码:
import java.util.*;
import java.math.*; class Solution {
public int findContentChildren(int[] g, int[] s) {
Queue<Integer> qg = new PriorityQueue<>();
Queue<Integer> qs = new PriorityQueue<>(); for(int i=0; i<g.length; i++){
qg.add(g[i]);
}
for(int i=0; i<s.length; i++){
qs.add(s[i]);
} while(!qg.isEmpty() && !qs.isEmpty()){
int tg = qg.peek();
int ts = qs.peek();//取顶部数据,不弹出,poll取顶部数据并弹出
/*System.out.println("qg:" + qg.peek());
System.out.println("qs:" + qs.peek());
System.out.println();*/
if(ts >= tg){
qg.remove();//移除队列顶部数据
}
qs.remove();
}
//System.out.println(qs.size());
return (g.length - qg.size());
}
} public class Main {
public static void main(String[] args){
/* Queue<Integer> queue = new PriorityQueue<>();
queue.add(1);
queue.add(2);
queue.add(3);
queue.remove();
System.out.println(queue.size());*/
Scanner scanner = new Scanner(System.in);
Solution solution = new Solution();
int n = scanner.nextInt();
int[] g = new int[n];
int m = scanner.nextInt();
int[] s = new int[m];
for(int i=0; i<n; i++){
g[i] = scanner.nextInt();
}
for(int i=0; i<m; i++){
s[i] = scanner.nextInt();
}
System.out.println(solution.findContentChildren(g, s));
}
}