二分
比较好理解的左侧右侧二分统一版本
r
是len - 1,
l + 1< r
作为判断条件
答案可能出现在l
或r
为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