[LeetCode] 1276. Number of Burgers with No Waste of Ingredients 不浪费原料的汉堡制作方案
Given two integers tomatoSlices
and cheeseSlices
. The ingredients of different burgers are as follows:
- Jumbo Burger:
4
tomato slices and1
cheese slice. - Small Burger:
2
Tomato slices and1
cheese slice.
Return [total_jumbo, total_small]
so that the number of remaining tomatoSlices
equal to 0
and the number of remaining cheeseSlices
equal to 0
. If it is not possible to make the remaining tomatoSlices
and cheeseSlices
equal to 0
return []
.
Example 1:
Input: tomatoSlices = 16, cheeseSlices = 7
Output: [1,6]
Explantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.
There will be no remaining ingredients.
Example 2:
Input: tomatoSlices = 17, cheeseSlices = 4
Output: []
Explantion: There will be no way to use all ingredients to make small and jumbo burgers.
Example 3:
Input: tomatoSlices = 4, cheeseSlices = 17
Output: []
Explantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.
Constraints:
0 <= tomatoSlices, cheeseSlices <= 107
这道题是关于做汉堡的问题,说是给了一些西红柿切片和芝士切片,让做两种汉堡,一种是巨无霸汉堡,需要4片西红柿切片和1片芝士切片,另一种是小汉堡,需要2片西红柿和1片芝士切片,问正好用完所有的切片,能分别做出两种汉堡多少个。这道题让博主想到了《分手厨房》这款小游戏,咚咚咚的切西红柿的声音在脑边回想起来,盘子扔的飞起。这里说了两种汉堡都只需要一片芝士,那么芝士的总数一定就是两个汉堡的个数,所以最简单的办法就是遍历和为 cheeseSlices 的两个数字的所有组合,然后再去计算其需要的西红柿切片个数是否正好等于给定的 tomatoSlices 就可以了,感觉应该算一道 Easy 的题目,参见代码如下:
解法一:
class Solution {
public:
vector<int> numOfBurgers(int tomatoSlices, int cheeseSlices) {
for (int i = 0; i <= cheeseSlices; ++i) {
if (i * 4 + (cheeseSlices - i) * 2 == tomatoSlices) {
return {i, cheeseSlices - i};
}
}
return {};
}
};
这道题其实是一道二元一次方程求解的题目,基本算是初中数学的知识,设巨无霸汉堡有x个,小汉堡有y个,西红柿切片个数为t,芝士切片个数为c,则可写出以下两个方程:
4x + 2y = t
x + y = c
求解可得:
x = t / 2 - c
y = 2c - t / 2
由于x和y的解必须是非负数,所有下列两个不等式必须同时成立:
t / 2 - c >= 0
2c - t / 2 >= 0
化简可得 t >= 2c && t <= 4c
,同时,因为两种汉堡都是需要偶数个西红柿切片,所以t必须是偶数,只要同时满足这个三个条件的t和c,才能得到x和y的正确解,所以其实这要一行代码就可以了,博主加了一行变量名称化简的操作,当三个条件满足的时候,直接按上面的等式求出x和y返回,否则返回空数组即可,参见代码如下:
解法二:
class Solution {
public:
vector<int> numOfBurgers(int tomatoSlices, int cheeseSlices) {
int t = tomatoSlices, c = cheeseSlices;
return (t % 2 == 0 && t >= 2 * c && t <= 4 * c) ? vector<int>{t / 2 - c, 2 * c - t / 2} : vector<int>();
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1276
参考资料:
https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/