Open azl397985856 opened 3 years ago
贪心。
贪心思想: 尽可能多地让最小的饼干满足胃口小一点的小孩, 刚刚满足小孩的胃口即可, 也就是让饼干最大可能地被利用~
先排序, 然后用指针i 遍历s数组, 接下来到g数组中找(j指针从0开始)。
发现1组满足条件的, 就把j 移动1位。
循环结束时, 返回 j。
不要把问题想复杂了。
实现语言: C++
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
// 双指针
int j = 0; // 遇到满足条件的情形, j才移动一步(同时是一个计数器)
for (int i = 0; i < s.size() && j < g.size(); ++i)
{
if (s[i] >= g[j]) j++;
}
return j;
}
};
class Solution {
public int findContentChildren(int[] g, int[] s) {
int res = 0;
Arrays.sort(g);
Arrays.sort(s);
int i = 0, j = 0;
while (i < g.length && j < s.length) {
if (g[i] <= s[j]) {
res++;
i++;
j++;
} else if (g[i] > s[j]) {
j++;
}
}
return res;
}
}
greedy. Sort the array of child and array of cookies. If the current cookie can satisfy the child, move on to next cookie and next child. Otherwise, check if next cookie can satisfy this child.
Time: O(nlogn) Space: O(1)
class Solution {
public int findContentChildren(int[] g, int[] s) {
int count=0;
Arrays.sort(g);
Arrays.sort(s);
int i=0,j=0;
while(i<g.length && j<s.length) {
if(s[j]>=g[i]) {
count++;
i++;
}
j++;
}
return count;
}
}
贪心。我们只能把不小于孩子胃口值的饼干给孩子,并且每块饼干最多只能给1个孩子。我们可以分别对孩子们按胃口值从小到大排序,对饼干按尺寸从小到大排序,将排好序的两个数组同时向后遍历,优先满足胃口值小的孩子。最后返回结果即可。
class Solution {
public int findContentChildren(int[] g, int[] s) {
// sort g and s, easy to compare
Arrays.sort(g);
Arrays.sort(s);
int gidx = 0, sidx = 0;
int res = 0;
while (gidx < g.length && sidx < s.length) {
// we can assign the cookie
if (g[gidx] <= s[sidx]) {
res++;
gidx++;
sidx++;
}
// we cannot assign the cookie, check next cookie
else {
sidx++;
}
}
return res;
}
}
复杂度分析
比较两个数组
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
int sum=0;
int lenG=g.size(),lenS=s.size();
sort(g.begin(),g.end());
sort(s.begin(),s.end());
int i=0,j=0;
while(i<lenG && j<lenS)
{
if(g[i]<=s[j])
{
sum+=1;
i+=1;
}
j+=1;
}
return sum;
}
};
时间复杂度:O(NLogN)
空间复杂度:O(1)
从大到小遍历孩子,选择最大的饼干,直到结束
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort(reverse = True)
s.sort(reverse = True)
s_index = 0
result = 0
for g_index, g_value in enumerate(g):
if s_index >= len(s):
break
if s[s_index] < g_value:
continue
result += 1
s_index += 1
return result
时间复杂度:O(N*logN)
空间复杂度:O(1)
贪心 双指针
def findContentChildren(self, g: List[int], s: List[int]) -> int:
if not s:
return 0
g.sort()
s.sort()
offset,index=0,0
while index+offset<len(s) and index<len(g):
if s[index+offset]<g[index]:
while s[index+offset]<g[index]:
offset+=1
if index+offset==len(s):
return index
index+=1
return index
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
if not g or not s:
return 0
g.sort()
s.sort()
result, g_l, s_l = 0, 0, 0
while g_l < len(g) and s_l < len(s):
if g[g_l] <= s[s_l]:
result += 1
g_l += 1
s_l += 1
else:
s_l += 1
return result
two pointer + greedy
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int i = 0; // pointer for children
int j = 0; // pointer for cookies
while(i < g.length && j < s.length) {
if(s[j] >= g[i]) {
i++;
j++;
} else {
j++;
}
}
return i;
}
}
空间复杂度: O(1)
时间复杂度: O(nlogn)
class Solution {
public int findContentChildren(int[] g, int[] s) {
// 尽量用小的饼干满足小孩
Arrays.sort(g);
Arrays.sort(s);
int j = 0; // 被满足小孩的个数
for (int i = 0; i < s.length && j < g.length; i++) {
if (s[i] >= g[j]) {
j += 1;
}
}
return j;
}
}
c Code:
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int gleft =0;
int sleft =0;
int count =0;
while(gleft< g.size() && sleft< s.size())
{
if(g[gleft]<=s[sleft])
{
count++;
gleft++;
sleft++;
}
else
sleft++;
}
return count;
}
};
https://leetcode.com/problems/assign-cookies/
class Solution {
public int findContentChildren(int[] g, int[] s) {
if(g == null || s == null){
return 0;
}
int res = 0;
Arrays.sort(g);
Arrays.sort(s);
int i = 0;
int j = 0;
while(i < g.length && j < s.length){
while(j < s.length && s[j] < g[i]){
j++;
}
if(j < s.length && s[j] >= g[i]){
res++;
i++;
j++;
}
}
return res;
}
}
Explanation
Python
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
s.sort(reverse=True)
g.sort(reverse=True)
gi, si = 0, 0
count = 0
while gi < len(g) and si < len(s):
if s[si] >= g[gi]:
count += 1
si += 1
gi += 1
return count
Complexity:
O(nlogn)
where n is max(len(g), len(s))O(1)
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
child = 0
cookie = 0
while child < len(g) and cookie < len(s):
if g[child] <= s[cookie]:
child += 1
cookie += 1
return child
time complexity: O(nlogn) space complexity: O(1)
var findContentChildren = function(g, s) {
var increase = function(a,b){return a-b;};
let res = 0;
let cookie = s.length-1;
let kid = g.length-1;
s.sort(increase);
g.sort(increase);
while (cookie >= 0 && kid >= 0){
if (g[kid] <= s[cookie]){
res++;
kid --;
cookie--;
}else{kid--;};
};
return res;
};
两个数组排序之后,按照size去满足尽量多的grady factor
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
s.sort()
g.sort()
i = 0
for j, greedy_factor in enumerate(g):
while i < len(s) and s[i] < greedy_factor:
i += 1
if i < len(s) and s[i] >= greedy_factor:
i += 1
else:
return j
return len(g)
m 为g的长度, n为s的长度 Time O(mlgm+nlgn + m +n) = O(mlgm+nlgn)
Space O(1)
题目比较简单,经典贪心法,child数组和cookie数组分别排序,child>cookie那就试下一个cookie,child<=cookie那就匹配上了,匹配上了就下一个cookie和下一个孩子
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
count = 0
cookie_index = 0
for child in g:
while cookie_index < len(s) and child > s[cookie_index]:
cookie_index += 1
if not cookie_index < len(s):
return count
count += 1
cookie_index += 1
return count
TC: O(nlogn) SC: O(1)
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int count = 0;
int i = 0, j = 0;
while (i < g.length && j < s.length) {
if (g[i] <= s[j]) {
count++;
i++;
j++;
} else {
j++;
}
}
return count;
}
https://leetcode.com/problems/assign-cookies/
const findContentChildren = function (g, s) {
g.sort(function (a, b) {
return a - b;
});
s.sort(function (a, b) {
return a - b;
});
let j = 0;
s.forEach((element) => {
if (element >= g[j]) {
j++;
}
});
return j;
};
Greedy. Sort both array at first. Then for each pair of child and cookie check whether the child can be content, if so, move to next child and cookie and add ans by one. If the child cannot be content, move to next cookie.
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g = sorted(g)
s = sorted(s)
i, j, ans = 0, 0, 0
while i < len(g) and j < len(s):
if g[i] <= s[j]:
i += 1
j += 1
ans += 1
else:
j += 1
return ans
Time: O(nlogn). n = max(length of children array, length of cookie array) Sapce: O(1)
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
ans = 0
if not s:
return 0
g.sort()
s.sort()
for gg in g:
for ss in s:
if ss >= gg:
ans += 1
s.remove(ss)
break
return ans
double pointers
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
ans = 0
if not s:
return 0
g.sort()
s.sort()
l = 0
r = 0
while l< len(g) and r < len(s):
if g[l]<=s[r]:
ans += 1
l += 1
r += 1
else:
r += 1
return ans
Time: O(nlogn). n = max(length of children array, length of cookie array) Sapce: O(1)
https://leetcode.com/problems/assign-cookies/
Greedy
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
if not s:
return 0
g.sort()
s.sort()
res = 0
g_i, s_i = len(g) - 1, len(s) - 1
while g_i >= 0 and s_i >= 0:
if g[g_i] <= s[s_i]:
res += 1
g_i -= 1
s_i -= 1
else:
g_i -= 1
return res
DP 时间复杂度: O(NlogN) 空间复杂度:O(N)
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int idxG = 0;
int idxS = 0;
int res = 0;
while(idxG < g.length && idxS < s.length) {
if(g[idxG] <= s[idxS]) {
res++;
idxG++;
idxS++;
} else {
idxS++;
}
}
return res;
}
}
O(nlogn)
O(1)
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
j = res = 0
for i in range(len(g)):
while j < len(s) and g[i] > s[j]:
j += 1
if j >= len(s):
break
res += 1
j += 1
return res
Time complexity: O(NlogN)
Space complexity: O(1)
O(nlgn), O(1)
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
gi, si = 0, 0
ret = 0
while gi < len(g) and si < len(s):
gn, sn = g[gi], s[si]
if gn <= sn:
ret += 1
gi += 1
si += 1
else:
si += 1
return ret
class Solution
{
public:
int findContentChildren(vector<int> &g, vector<int> &s)
{
std::sort(g.begin(), g.end());
std::sort(s.begin(), s.end());
int i{ 0 };
int j{ 0 };
int res{ 0 };
// Notice each element in the cookie array can only be assigned to one child
while (i < g.size() && j < s.size()) {
if (s[j] >= g[i]) {
res++;
// s[j] -= g[i];
j++;
i++;
} else {
j++;
}
}
return res;
}
};
贪心。
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int numOfChildren = g.size(), numOfCookies = s.size();
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;
}
};
贪心
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int gl = g.length;
int sl = s.length;
int res= 0;
for(int i = 0,j = 0;i<gl&&j<sl;i++,j++){
while(j<sl && s[j]<g[i]){
j++;
}
if(j<sl){
res++;
}
}
return res;
}
}
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;
}
}
时间复杂度:O(MlogM+NlogN) 空间复杂度:O(logM+logN)
思路: 关键是排序 + 双指针遍历 保证蛋糕尺寸最小的给胃口最小的儿童,否则换蛋糕
func findContentChildren(g []int, s []int) int {
sort.Ints(g)
sort.Ints(s)
i,j,out:=0,0,0
for i < len(g)&&j<len(s){
if s[j] >=g[i]{
i++
j++
out++
}else{
j++
}
}
return out
}
时间复杂度:O(nlogn) 空间复杂度O(1)
title: "Day 65 455. 分发饼干" date: 2021-11-13T08:54:19+08:00 tags: ["Leetcode", "c++", "Greed"] categories: ["91-day-algorithm"] draft: true
假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。
对每个孩子 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 * 104
0 <= s.length <= 3 * 104
1 <= g[i], s[j] <= 2^31 - 1
- 1、贪心法,优先满足最近的原则,排序两个数组,优先满足胃口最小的孩子,返回满足孩子的个数即可。
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int n = g.size(), m = s.size();
int count = 0;
for (int i = 0, j = 0; i < n && j < m; i++, j++) {
while (j < m && g[i] > s[j]) j++;
if (j < m) count++;
}
return count;
}
};
时间复杂度:O(n)
空间复杂度:O(1)
class 分发饼干_455 {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(s);
Arrays.sort(g);
int i=0, j=0, res=0;
// 贪心模板 : 不断尝试 用小的匹配大的
// 双指针
// while () { 最小的饼干能满足当前胃口的孩子 res ++ 否则用大点的饼干来喂当前的孩子 }
while(i < s.length && j < g.length) {
if(s[i] >= g[j]) {
i ++;
j ++;
res ++;
} else {
i ++;
}
}
return res;
}
}
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
s.sort()
g.sort()
res = 0
len_n = min(len(g),len(s))
i,j = len(g)-1 ,len(s)-1
while i >=0 and j>=0:
print(g[i],s[j])
if g[i]<=s[j]:
res+=1
i-=1
j-=1
else:
i-=1
return res
var findContentChildren = function (g, s) {
g = g.sort((a, b) => a - b);
s = s.sort((a, b) => a - b);
let result = 0;
let index = s.length - 1;
for (let i = g.length - 1; i >= 0; i--) {
if (index >= 0 && s[index] >= g[i]) {
result++;
index--;
}
}
return result;
};
排序+双指针
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(),g.end());
sort(s.begin(),s.end());
int i=0,j=0,res=0;
int glen=g.size(),slen=s.size();
while(i<glen&&j<slen){
if(s[j]>=g[i]){
res++;
i++;
j++;
}else{
j++;
}
}
return res;
}
};
复杂度分析
Greedy
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
res = i = j = 0
while(i<len(g) and j<len(s)):
if s[j] >= g[i]:
res+=1
i+=1
j+=1
return res
Space: O(1) Time: O(nlogn)
https://leetcode-cn.com/problems/assign-cookies/
假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。
对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
先对孩子的胃口、饼干尺寸从小到大排序;然后比较。
C Code:
int findContentChildren(int* g, int gSize, int* s, int sSize){
int cmpfunc (const void * a, const void * b){
return ( *(int*)a - *(int*)b );
}
qsort(g,gSize,sizeof(int),cmpfunc);
qsort(s,sSize,sizeof(int),cmpfunc);
int p1=0,p2=0;
int cnt=0;
while(p2<sSize&&p1<gSize){
if(s[p2]>=g[p1]){
p1++;
p2++;
cnt++;
}else{
if(s[p2]<g[p1]){
p2++;
}
}
}
return cnt;
}
复杂度分析
令 n 为数组长度。
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
res = 0
gi,si =0,0
while (gi < len(g) and si < len(s)):
if s[si] < g[gi]:
si += 1
else :
gi += 1
si += 1
res +=1
return res
排序,为 s、g 各分配一指针,根据条件向后移
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int i = 0, j = 0, res = 0;
while (i < g.length && j < s.length) {
if (s[j] >= g[i]) {
res++;
i++;
j++;
} else {
j++;
}
}
return res;
}
}
时间: O(mlogm + nlogn) \ 空间: O(logm + logn)
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
m, n = len(g), len(s)
i, j, count = 0, 0, 0
while i < m and j < n:
while j < n and g[i] > s[j]:
j += 1
if j < n:
count += 1
i += 1
j += 1
return count
先对两个数组进行排序
尽可能将小的饼干先给胃口小的孩子
如果现在这个 饼干可以满足这个孩子, 那么 指向两个数组的指针 都 +1, 并且 计数的 num 也 +1
否则说明现在都饼干无法满足现在胃口最小的孩子的胃口, 那么 指向下一块饼干直到能满足现在胃口最小的孩子或者没有多余的饼干位置
最后返回 num
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
i_s, i_g = 0, 0
num = 0
while i_s < len(s) and i_g < len(g):
if s[i_s] >= g[i_g]:
num += 1
i_s += 1
i_g += 1
else:
i_s += 1
return num
n, m 为 g 和 s 的长度
时间复杂度: O(nlogn + mlogm) O(nlogn) 和 O(mlogm) 是对两个数组的排序复杂度, 遍历的复杂度是 O(n+m)
空间复杂度: O(1)
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
ptr = 0
for size in s:
if size<g[ptr]: continue
else:
ptr+=1
if ptr>len(g)-1: break
return ptr
动态规划
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int ng = g.length , ns = s.length;
int[] dp = new int[ns+1];
int nc = 0;
for(int i = 1 ; i <= ns ;i++){
dp[i] = dp[i-1];
for(int j = nc + 1 ; j <= ng ; j++){
if(s[i-1] >= g[j-1]){
dp[i] = dp[i-1] + 1;
break;
}
}
nc = dp[i];
}
return dp[ns];
}
}
时间复杂度:O(ns * ng) 空间复杂度:O(ns)
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int numOfChildren = g.size(), numOfCookies = s.size();
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;
}
};
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
result = 0
i = 0
j = 0
while i < len(g) and j < len(s):
if g[i] <= s[j]:
result += 1
i += 1
j += 1
else:
j += 1
return result
Time: O(nlogn) - sorting
Space: O(1)
/**
* @param {number[]} g
* @param {number[]} s
* @return {number}
*/
const findContentChildren = function(g, s) {
g.sort((a, b) => a - b);
s.sort((a, b) => a - b);
let count = 0;
let i = 0;
for (let j = 0; j < s.length; j++) {
if (i === g.length) break;
if (s[j] >= g[i]) {
count += 1;
i += 1;
}
}
return count;
};
https://leetcode-cn.com/problems/assign-cookies/
Greedy
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
i = 0
j = 0
count = 0
while(i < len(g) and j < len(s)):
# 如果此时孩子的食量比饼干分量大,那么在不超出范围的情况下,往后遍历
while(j < len(s) and s[j] < g[i]):
j += 1
# 如果在有限饼干范围内,找到了满足孩子胃口的那一块,就继续往后遍历,并且计数值+1
if (j < len(s)):
count += 1
i += 1
j += 1
return count
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
res = 0
gi,si =0,0
while (gi < len(g) and si < len(s)):
if s[si] < g[gi]:
si += 1
else :
gi += 1
si += 1
res +=1
return res
贪心
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int i = 0, j = 0, ans = 0;
while (i < g.length && j < s.length) {
if (s[j] >= g[i]) {
++i;
++j;
++ans;
} else {
++j;
}
}
return ans;
}
}
贪心的基本思想,尽量用小饼干去喂饱小胃口的孩子,这样就能喂饱最多的孩子。所以先排序,再比较
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int idx = 0;
for (int i=0; i<s.length && idx<g.length; i++) {
if (s[i] >= g[idx]) {
idx++;
}
}
return idx;
}
}
TC: O(NLogN) 排序 SC: O(LogN) 排序
455. 分发饼干
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/assign-cookies/
前置知识
暂无
题目描述