题目:
小扣在秋日市集选择了一家早餐摊位,一维整型数组 staple 中记录了每种主食的价格,一维整型数组 drinks 中记录了每种饮料的价格。小扣的计划选择一份主食和一款饮料,且花费不超过 x 元。请返回小扣共有多少种购买方案。
注意:答案需要以 1e9 + 7 (1000000007) 为底取模,如:计算初始结果为:1000000008,请返回 1
思路:
刚开始采用了暴力解法,然后显示超时了
class Solution:
def breakfastNumber(self, staple: List[int], drinks: List[int], x: int) -> int:
m=len(staple)
n=len(drinks)
res=0
for i in range(m):
for j in range(n):
if staple[i]+drinks[j]<=x:
res+=1
a=int(1e9)
return res%a
转而改进,先对数组排序,对drinks逆序判断:若drinks中最小的元素与当前staple元素相加都大于x,那staple之后的元素则不用再判断了。
解答:
class Solution:
def breakfastNumber(self, staple: List[int], drinks: List[int], x: int) -> int:
staple.sort()
drinks.sort()
m=len(staple)
j=len(drinks)-1
res=0
a=1000000007
for i in range(m):
while j>=0 and staple[i]+drinks[j]>x:
j-=1
if j==-1:
break
res=(res+j+1)%a
return res