問題:
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.
大意:
假設(shè)你是一個很棒的父母,并且想要拍給你的孩子一些餅干。但是你應(yīng)該給每個小孩至少一個餅干训枢。每個小孩 i 有一個貪婪因子 gi晤揣,這是那個小孩能滿足的餅干的最小尺寸;而每個餅干 j 都有一個尺寸 sj,如果 sj >= gi,我們就可以把 j 餅干給小孩 i,并且小孩 i 會得到滿足揭北。你的目標是給盡量多的小孩餅干并且返回最大數(shù)量。
注意:
你可以假設(shè)貪婪因子始終是正數(shù)使套。
你不能給超過一塊餅干給一個小孩罐呼。
例1:輸入: [1,2,3], [1,1]
輸出:1
解釋:你有三個小孩和兩塊餅干,三個小孩的貪婪因子為1侦高、2嫉柴、3。雖然你有兩塊餅干奉呛,但是因為它們的尺寸都是1计螺,所以你只能讓貪婪因子是1的小孩滿足。所以你需要輸出1瞧壮。例2:
輸入: [1,2], [1,2,3]
輸出:2
解釋:你有兩個小孩和三塊餅干登馒,兩個小孩的貪婪因子是1、2咆槽。你有三塊餅干并且他們足夠大來滿足所有的小孩陈轿,你需要輸出2。
思路:
這乍看之下有點復雜秦忿,涉及到一個類似最優(yōu)分配的問題麦射,但其實是簡化了的,因為每個小孩最多只能給一塊餅干灯谣,只用考慮盡量給的小孩多就可以了潜秋。
簡單地說就是看每個小孩有沒有剩下的餅干能滿足他,有就給他胎许,沒有就過峻呛,但是為了給的盡量多,所以大餅干盡量給更貪婪的小孩子辜窑,給每個小孩的餅干盡量維持剛好滿足他就行了钩述,不過如果實在只能找到大餅干給他那也行,反正最后只要求小孩數(shù)量穆碎,給誰都是給切距。
我們先將餅干尺寸和小孩需求都排個序,然后從小到大去遍歷地給惨远。在遍歷過程中可以取個巧谜悟,兩個排序后的數(shù)組都設(shè)一個標記,一起往后移北秽,餅干大小不滿足就移餅干的標記葡幸,看看后面的餅干能不能滿足他,只有滿足了才移小孩的標記贺氓,因為如果這個小孩都不能滿足蔚叨,后面更貪婪的小孩更加滿足不了。循環(huán)的結(jié)束條件就是小孩或者餅干的標記二者有一個到了數(shù)組的尾部辙培,就算停止蔑水。
代碼(Java):
public class Solution {
public int findContentChildren(int[] g, int[] s) {
if (g.length == 0 || s.length == 0) return 0;
Arrays.sort(g);
Arrays.sort(s);
int i = 0;
int j = 0;
int result = 0;
while (!(i >= g.length || j >= s.length)) {
if (s[j] >= g[i]) {
result ++;
j++;
i++;
} else {
j++;
}
}
return result;
}
}
合集:https://github.com/Cloudox/LeetCode-Record