Re: [閒聊] 每日leetcode
2563. Count the Number of Fair Pairs
## 思路
任兩數相加介於lower, upper之間
先排序
用Two pointer分別計算小於等於upper跟lower-1 Pair個數並相減
## Code
```
class Solution:
def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:
nums.sort()
n = len(nums)
def get_count(val):
res = 0
left, right = 0, n-1
while left < right:
if nums[left] + nums[right] <= val:
res += right - left
left += 1
else:
right -= 1
return res
return get_count(upper) - get_count(lower-1)
```
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 94.156.205.47 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1731497147.A.2B7.html
→
11/13 19:58,
1年前
, 1F
11/13 19:58, 1F
討論串 (同標題文章)
完整討論串 (本文為第 1118 之 1548 篇):