刷题记录-day9 (跳台阶扩展问题、买卖股票的最好时机(一)、数组中重复的数字、不用加减乘除做加法)

1.跳台阶扩展问题

在这里插入图片描述
在这里插入图片描述

class Solution:
    def jumpFloorII(self , number: int) -> int:
        # write code here
        # n阶台阶,可以设想,最后一步为一步跳、两步跳、三步跳等
        # 可以列出等式f(n) = f(n-1) + f(n-2) +...+ f(1)
        # 此方法为图中粉红色
        res = 1
        for i in range(1, number):
            res = res * 2
        return res

        # 此方法为图中灰色
        return pow(2,number-1)

2.买卖股票的最好时机(一)

在这里插入图片描述

class Solution:
    def maxProfit(self , prices: List[int]) -> int:
        # write code here
        # 利用之前动态规划的思想,使用res始终保存能够获得的最大利润
        # 根据题意,我们需要在买入时是最低价,卖出时为最低价后面的最大值
        # 因此最低价也是需要记录保存的数值,比如[8,9,2,5,4,7,1],如果我们始终使用8作为最低价,我们就会错过后面的2
        # 因此遇到比8更小的价,我们就马上将其作为买入时间节点。
        # 可能会担心把最低价换了,后来发现后面的没有可以赚的时间了,没关系,我们的res已经替我们保存好着历史最高利润
        res = 0
        min_ = prices[0]
        for i in range(1, len(prices)):
            temp = prices[i] - min_
            if res <= temp:
                res = temp
            if prices[i] < min_:
                min_ = prices[i]
        return res

3.数组中重复的数字

在这里插入图片描述

class Solution:
    def duplicate(self , numbers: List[int]) -> int:
        # write code here
        # 另取字典存储每个数字有多少个,两个遍历,一次遍历数组,一次遍历字典
        count_dict = {}
        for num in numbers:
            if num not in count_dict.keys():
                count_dict[num] = 1
                continue
            count_dict[num] += 1
            
        for k,v in count_dict.items():
            if v > 1:
                return k
        return -1

4. 不用加减乘除做加法

在这里插入图片描述

class Solution:
    def Add(self , num1: int, num2: int) -> int:
        # write code here
        return sum([num1,num2])

        # 看不懂的位运算方法
        x = 0xffffffff
        num1 = num1 & x
        num2 = num2 & x
        a, b = num1, num2
        while b != 0:
            a, b = a ^ b, (a & b) << 1 & x
        return a if a <= 0x7fffffff else ~(a ^ x)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值