1276. 不浪费原料的汉堡制作方案
难度: 中等
题目大意:
给你两个整数 tomatoSlices
和 cheeseSlices
,分别表示番茄片和奶酪片的数目。不同汉堡的原料搭配如下:
- **巨无霸汉堡:**4 片番茄和 1 片奶酪
- **小皇堡:**2 片番茄和 1 片奶酪
请你以 [total_jumbo, total_small]
([巨无霸汉堡总数,小皇堡总数])的格式返回恰当的制作方案,使得剩下的番茄片 tomatoSlices
和奶酪片 cheeseSlices
的数量都是 0
。
如果无法使剩下的番茄片 tomatoSlices
和奶酪片 cheeseSlices
的数量为 0
,就请返回 []
。
0 <= tomatoSlices <= 10^7
0 <= cheeseSlices <= 10^7
思路
很显然这题是数学问题,我们假设有x
个巨无霸汉堡,y
个小皇包,那么肯定满足
{
4
x
+
y
=
t
o
m
a
t
o
S
l
i
c
e
s
x
+
y
=
c
h
e
e
s
e
S
l
i
c
e
s
\begin{cases} 4x + y = tomatoSlices \\ x + y = cheeseSlices \end{cases}
{4x+y=tomatoSlicesx+y=cheeseSlices
很容易解得:
{
x
=
t
o
m
a
t
o
S
l
i
c
e
s
−
2
∗
c
h
e
e
s
e
S
l
i
c
e
s
2
y
=
c
h
e
e
s
e
S
l
i
c
e
s
−
x
\begin{cases} x = \frac{tomatoSlices - 2*cheeseSlices}{2} \\ y = cheeseSlices - x \end{cases}
{x=2tomatoSlices−2∗cheeseSlicesy=cheeseSlices−x
那么我们只需要判断tomatoSlices - 2*cheeseSlices
是不是2
的倍数,并且保证数据都要大于等于0
就好了
代码实现:
class Solution {
public:
vector<int> numOfBurgers(int tomatoSlices, int cheeseSlices) {
int b = tomatoSlices - 2 * cheeseSlices;
int a = b >> 1;
if (a * 2 == b && a >= 0 && cheeseSlices - a >= 0) {
return {a, cheeseSlices - a};
}
return {};
}
};
时间复杂度: O ( 1 ) O(1) O(1)
结束了