算法笔记: 力扣#455 分发饼干

问题描述


解法


分析

Python 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class :
def findContentChildren(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
g.sort()
s.sort()
g_len = len(g) - 1
c = 0
for s_i in s:
if c > g_len:
break
if s_i >= g[c]:
c += 1
return c

Java 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
class {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int g_len = g.length - 1;
int c = 0;
for(int s_i : s){
if(c > g_len){ break; }
if(s_i >= g[c]){ c++; }
}
return c;
}
}

时间复杂度

O(nlogn).

空间复杂度

O(1).

链接


455. Assign Cookies
455. 分发饼干
(English version) Algorithm Notes: Leetcode#455 Assign Cookies