题目描述
小扣在秋日市集选择了一家早餐摊位,一维整型数组 staple 中记录了每种主食的价格,一维整型数组 drinks 中记录了每种饮料的价格。小扣的计划选择一份主食和一款饮料,且花费不超过 x 元。请返回小扣共有多少种购买方案。
注意:答案需要以 1e9 + 7 (1000000007) 为底取模,如:计算初始结果为:1000000008,请返回 1
思路:只想到暴力枚举,两个for
代码
class Solution {
public int breakfastNumber(int[] staple, int[] drinks, int x) {
int count = 0;
for(int i = 0 ; i<staple.length; i++){
for(int j = 0 ; j<drinks.length ;j ++)
{
if((staple[i] + drinks[j])<=x)
count++;
}
}
return count;
}
}
没通过 ,超时。。。。。。。
改进
想法是先处理下两个数组,把单品超过x的删除。
class Solution {
public int breakfastNumber(int[] staple, int[] drinks, int x) {
int count = 0;
List<Integer> a = new ArrayList<>();
List<Integer> b = new ArrayList<>();
for(int i = 0 ; i<staple.length; i++){
if(staple[i]<x)
a.add(staple[i]);
}
for(int i = 0 ; i<drinks.length; i++){
if(drinks[i]<x)
b.add(drinks[i]);
}
for(int i = 0 ; i<a.size(); i++){
for(int j = 0 ; j<b.size() ;j ++)
{
if((a.get(i) + b.get(j))<=x)
count++;
}
}
return count;
}
}
经过我的一方改进 ,还是超时。绷不住了。。。。
看了下各种答案也云里雾里,下次吧
题解
反思总结