Leetcode: 贪心算法
admin
2024-01-29 20:51:08

leetcode 贪心算法汇总

Leetcode 455: Assign Cookies

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 g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], 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.

Example 1:

Input: g = [1,2,3], s = [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.
 class Solution {public int findContentChildren(int[] g, int[] s) {Arrays.sort(g);Arrays.sort(s);int a_pointer = 0;int b_pointer = 0;while (a_pointer < g.length && b_pointer < s.length) {if (g[a_pointer] <= s[b_pointer]) {a_pointer++;b_pointer++;} else {b_pointer++;}}return a_pointer;}
}

相关内容

热门资讯

摸鱼、钓虾、吃瓜、赏荷…初夏时... 这个周末,一场场充满野趣的“田园嘉年华”在沪郊金山多个农场上演,吸引众多市民带着孩子下乡来,赛跑、吃...
原创 戚... 5月28日,北京环球影城迎来了一对温暖的家庭画面:戚薇和李承铉携三岁半的儿子Seven现身游玩。现场...
滹沱河畔 遇见“诗和远方” 图为市民在滹沱河畔休闲娱乐。 初夏五月,惠风和畅。徜徉在石家庄滹沱河生态区(城区段),澄澈河水蜿蜒...
在迪士尼排队两小时,我才看清V... 文丨沈理 在网上看到一则新闻: 上海迪士尼,创极速光轮排队区。一个父亲牵着七八岁的儿子,已经在烈日...
重庆文旅喊你去吃火锅、观山水、... 本网讯(草原云·正北方网记者 马丽侠)火锅、机车、文创、演艺……5月28日下午,重庆市文化和旅游发展...