常用刷题模板

二分
比较好理解的左侧右侧二分统一版本
rlen - 1, l + 1< r作为判断条件
答案可能出现在lr为Index的数据上 所以要判断之后返回

def findLeft():
    nonlocal A, target
    l, r = 0, len(A) - 1
    while l + 1 < r:
        mid = (l + r) // 2
        if A[mid] >= target:
            r = mid
        else:
            l = mid
    if A[l] == target:
        return l
    if A[r] == target:
        return r
    return -1
def findRight():
    nonlocal A, target
    l, r = 0, len(A) - 1
    while l + 1 < r:
        mid = (l + r) // 2
        if A[mid] <= target:
            l = mid
        else:
            r = mid
    if A[r] == target:
        return r
    if A[l] == target:
        return l
    return -1
if not A:
    return [-1, -1]
return [findLeft(), findRight()]

一些python数据结构
python中的 collections.OrderedDict() push的时候会放在末尾, 删除元素不影响其他元素位置, .popitem可以指定删除后缀或前缀元素

class LRUCache:

    def __init__(self, capacity: int):
        # 末尾新 头老
        self.data = collections.OrderedDict()
        self.capacity = capacity


    def get(self, key: int) -> int:
        res = -1
        if key in self.data:
            res = self.data[key]
            del self.data[key]
            self.data[key] = res
        return res

    def put(self, key: int, value: int) -> None:
        # 只有push会更新 所以如果存在 要先删除 然后再push 否则就order不会发生变化
        if key in self.data:
            del self.data[key]
        self.data[key] = value
        if len(self.data) > self.capacity:
            self.data.popitem(last = False) #删除头结点 代表旧的


#### sort重写
最大数
class LargerNumKey(str):
    def __lt__(x, y):
        return x+y < y+x
class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        nums = [str(i) for i in nums]
        nums.sort(key=LargerNumKey, reverse = True)
        while len(nums) > 1 and nums[0] == '0':
            del nums[0]
        res = ''.join(nums)
        return res
————————————————
版权声明:本文为CSDN博主「lsxkugou」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43651292/article/details/122532351
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值