Re: [闲聊] 每日leetcode

楼主: DJYOMIYAHINA (通通打死)   2024-11-13 23:10:30
用一堆bisect function可以过
但其实insort是O(N) 所以这样是O(N^2)
想当然是垫底
看答案
原来先sort+two pointer也行
我好笨
def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:
traveled = []
ans = 0
for num in nums:
idx_r = bisect_right(traveled, upper-num)
idx_l = bisect_left(traveled, lower-num)
ans += (idx_r-idx_l)
insort(traveled, num)
return ans
作者: oin1104 (是oin的说)   2024-11-13 23:40:00
大师
作者: dont   2024-11-13 23:49:00
也可以先把nums排序后 对[i+1,n) 两次做binary searchidx_r = bisect.bisect_right(nums, upper-nums[i], i+1)

Links booklink

Contact Us: admin [ a t ] ucptt.com