1.
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
n, m = len(g), len(s)
i = j = count = 0
while i < n and j < m:
while j < m and g[i] > s[j]:
j += 1
if j < m:
count += 1
i += 1
j += 1
return count
链接:https://leetcode-cn.com/leetbook/read/greedy/rveyb6/
这里面的
(self, g: List[int], s: List[int]) -> int
是type hints,是Python 3.5新加的功能。类型建议符并非强制规定和检查,也就是说即使传入的实际参数与建议参数不符,也不会报错。
函数参数中的“:”是参数的类型建议符(告诉程序员希望传入的实参的类型)。
函数后面跟着的“->”是函数返回值的类型建议符(用来说明该函数返回的值是什么类型)。
2.
同样的程序用C++进行编写
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;
}
};
链接:https://leetcode-cn.com/leetbook/read/greedy/rveyb6/
这里的vector<int>& g就相当于int &a = b, vector是一个能够存放任意类型的动态数组,能够增加和压缩数据,定义一个整形vector引用变量
- int a = b; 定义了一个int类型变量a,将b的值赋给a;
- int &a = b; 定义了b的一个别名,a与b完全等价,对a操作就是对b操作,可以输出a与b的地址&a、&b,发现地址相同。
3. 时间复杂度和空间复杂度
C++ new的用法_见牛羊的博客-CSDN博客_c++ new
参考这篇文章