力扣学习笔记-贪心算法(1)

 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

参考这篇文章

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值