给你两个整数 tomatoSlices
和 cheeseSlices
,分别表示番茄片和奶酪片的数目。不同汉堡的原料搭配如下:
- 巨无霸汉堡:4 片番茄和 1 片奶酪
- 小皇堡:2 片番茄和 1 片奶酪
请你以 [total_jumbo, total_small]
([巨无霸汉堡总数,小皇堡总数])的格式返回恰当的制作方案,使得剩下的番茄片 tomatoSlices
和奶酪片 cheeseSlices
的数量都是 0
。
如果无法使剩下的番茄片 tomatoSlices
和奶酪片 cheeseSlices
的数量为 0
,就请返回 []
。
思路:理解为鸡兔同笼问题,设巨无霸汉堡有x个,小皇堡有y个,列出方程
4x+2y=tomatoSlices
,x+y=cheeseSlices
,使的方程组有解即可。
public List<Integer> numOfBurgers(int tomatoSlices, int cheeseSlices) {
List<Integer> result = new ArrayList<>();
// 解方程组
int x = (tomatoSlices - 2 * cheeseSlices) / 2;
int y = cheeseSlices - x;
// 验证解是否有效
if (x >= 0 && y >= 0 && 4 * x + 2 * y == tomatoSlices && x + y == cheeseSlices) {
result.add(x);
result.add(y);
}
return result;
}