LCP 18. 早餐组合
- 题号:力扣LCP18
- 知识点:二分查找,双指针
- 目标完成度:36/150
- 总结
题干:
方法1 二分查找:
- 1.总体思路:遍历
staple
,计算剩余的钱,在drink
中查找小于等于剩余的前的商品数量,这一步使用二分查找def lessNum(nums, target)
class Solution:
def breakfastNumber(self, staple: List[int], drinks: List[int], x: int) -> int:
# 二分查找,寻找target的右边界
def lessNum(nums, target):
left = 0
right = len(nums) - 1
while left < right:
mid = left + (right - left)//2
if nums[mid] < target:
left = mid + 1
if nums[mid] > target:
right = mid
if nums[mid] == target:
left = mid + 1
if nums[left] > target:
return left
if nums[left] <= target and left == len(nums)-1:
return left+1
ans = 0
# 以小的数组做遍历
if len(staple) < len(drinks):
drinks.sort()
for s in staple:
if s > x:
continue
# d 是剩余的签
d = x - s
# 查找drinks中<=d的元素的个数,二分查找法
ans += lessNum(drinks, d)
else:
staple.sort()
for d in drinks:
if d > x:
continue
s = x - d
ans += lessNum(staple, s)
return ans%1000000007
方法2 双指针:
- 1.首先对两个数组排序
- 2.定义两个标记位(指针),
left
指向staple
的首位置,right
指向drinks
的末位置。 - 3.
left
每递增一次,都要不断收缩right
,以满足staple[left] + drinks[right] <= x
,此时right
指向的是满足条件的右边界,即第一次满足staple[left] + drinks[right] <= x
的位置
class Solution:
def breakfastNumber(self, staple: List[int], drinks: List[int], x: int) -> int:
drinks.sort()
staple.sort()
left = 0
right = len(drinks) - 1
ans = 0
while left<len(staple) and right>=0:
if staple[left] + drinks[right] <= x:
ans += (right + 1)
left += 1
else:
right -= 1
return ans%1000000007