LCP 18. 早餐组合
第一次写的情况,超时。
public class Solution {
public int BreakfastNumber(int[] staple, int[] drinks, int x) {
Array.Sort(staple);
Array.Sort(drinks);
// 最后结果
int res = 0;
// 同样价格的主食个数
int count = 0;
// 当前的主食价格
int temp = staple[0];
// 当前主食能搭配的饮料个数
int drinkNum = 0;
// 最高价格的主食搭配的饮料数量
foreach(int i in drinks){
if(temp + i <= x){
drinkNum++;
}else{
break;
}
}
foreach(int i in staple){
if(i == temp){
// 如果主食价格相同则同样价格主食数加一
count++;
}else{
// 如果主食价格变低,则重新计算搭配饮料数
res += (count * drinkNum);
count = 1;
temp = i;
drinkNum = 0;
foreach(int j in drinks){
if(temp + j <= x){
drinkNum++;
}else{
break;
}
}
}
}
// 最后一种主食的搭配饮料数没有加入结果
res += (count * drinkNum);
return res % (1000000007);
}
}
题解中的双指针方法。
public class Solution {
public int BreakfastNumber(int[] staple, int[] drinks, int x) {
Array.Sort(staple);
Array.Sort(drinks);
// 看题解学到的双指针
int res = 0;
int stapleLength = staple.Length;
int drinksLength = drinks.Length;
int i = 0;
int j = drinksLength - 1;
while(i < stapleLength && j >= 0){
if(staple[i] + drinks[j] <= x){
res = (res + j + 1) % (1000000007);
i++;
}else{
j--;
}
}
return res;
}
}
第一种方法最差的时间复杂度为O(mn),过于暴力。超时是正常现象。还是要善用双指针,学好数学啊。