题目:
小扣在秋日市集选择了一家早餐摊位,一维整型数组 staple 中记录了每种主食的价格,一维整型数组 drinks 中记录了每种饮料的价格。小扣的计划选择一份主食和一款饮料,且花费不超过 x 元。请返回小扣共有多少种购买方案。
注意:答案需要以 1e9 + 7 (1000000007) 为底取模,如:计算初始结果为:1000000008,请返回 1。
思路:先排序,然后一个左一个右
代码:
class Solution {
public int breakfastNumber(int[] staple, int[] drinks, int x) {
Arrays.sort(staple);
Arrays.sort(drinks);
int i = 0;
int j = drinks.length - 1;
long ans = 0;
while (i < staple.length && j >= 0) {
if (staple[i] + drinks[j] <= x) {
// 注意这里不是j - i + 1
ans += j + 1;
i++;
ans %= 1_000_000_007;
} else {
j--;
}
}
return (int) ans % 1_000_000_007;
}
}
性能:
时间复杂度o(nlogn)n=max(length1, length2)
空间复杂度o(1)
1353

被折叠的 条评论
为什么被折叠?



