小扣在秋日市集选择了一家早餐摊位,一维整型数组 staple
中记录了每种主食的价格,一维整型数组 drinks
中记录了每种饮料的价格。小扣的计划选择一份主食和一款饮料,且花费不超过 x
元。请返回小扣共有多少种购买方案。
注意:答案需要以 1e9 + 7 (1000000007)
为底取模,如:计算初始结果为:1000000008
,请返回 1
示例 1:
输入:
staple = [10,20,5], drinks = [5,5,2], x = 15
输出:
6
解释:小扣有 6 种购买方案,所选主食与所选饮料在数组中对应的下标分别是:
第 1 种方案:staple[0] + drinks[0] = 10 + 5 = 15;
第 2 种方案:staple[0] + drinks[1] = 10 + 5 = 15;
第 3 种方案:staple[0] + drinks[2] = 10 + 2 = 12;
第 4 种方案:staple[2] + drinks[0] = 5 + 5 = 10;
第 5 种方案:staple[2] + drinks[1] = 5 + 5 = 10;
第 6 种方案:staple[2] + drinks[2] = 5 + 2 = 7。
示例 2:
输入:
staple = [2,1,1], drinks = [8,9,5,1], x = 9
输出:
8
解释:小扣有 8 种购买方案,所选主食与所选饮料在数组中对应的下标分别是:
第 1 种方案:staple[0] + drinks[2] = 2 + 5 = 7;
第 2 种方案:staple[0] + drinks[3] = 2 + 1 = 3;
第 3 种方案:staple[1] + drinks[0] = 1 + 8 = 9;
第 4 种方案:staple[1] + drinks[2] = 1 + 5 = 6;
第 5 种方案:staple[1] + drinks[3] = 1 + 1 = 2;
第 6 种方案:staple[2] + drinks[0] = 1 + 8 = 9;
第 7 种方案:staple[2] + drinks[2] = 1 + 5 = 6;
第 8 种方案:staple[2] + drinks[3] = 1 + 1 = 2;
提示:
1 <= staple.length <= 10^5
1 <= drinks.length <= 10^5
1 <= staple[i],drinks[i] <= 10^5
1 <= x <= 2*10^5
示例代码1:
【下面代码耗时过于严重,不予采纳】
class Solution(object):
def breakfastNumber(self, staple, drinks, x):
"""
:type staple: List[int]
:type drinks: List[int]
:type x: int
:rtype: int
"""
staple.sort()
drinks.sort()
count = 0
for i in staple:
for j in drinks:
if i + j <= x:
count += 1
else:
break
return count
示例代码2:
class Solution(object):
def breakfastNumber(self, staple, drinks, x):
"""
:type staple: List[int]
:type drinks: List[int]
:type x: int
:rtype: int
"""
staple.sort()
drinks.sort()
n, m = len(staple), len(drinks)
count = 0
i, j = 0, m-1
while i < n and j >= 0:
if staple[i] + drinks[j] <= x:
count += j+1
i += 1
else:
j -= 1
return count % 1000000007
双指针:i, j 分别指向排序后的 staple 和 drinks 的头尾, 一个向后遍历,一个向前遍历
时间复杂度:O(mlogm + nlogn + m + n)
时间复杂度:O(1)
1. if staple[i] + drinks[j] <= x:
说明第 i 个 staple 和 前 j+1 个 drinks 都满足条件(因为已经排序),所以这次有 j+1 个满足条件的组合;然后 i++;
2. if staple[i] + drinks[j] > x:
说明当前值过大,那么要减小和,就把 j 往前移,即 j-- ,继续找下一个满足条件的 i 和 j