题目地址:
https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/description/
给定番茄数 t t t和奶酪数 c c c,第一类汉堡需要 4 4 4个番茄和 1 1 1个奶酪,第二类汉堡需要 2 2 2个番茄和 1 1 1个奶酪。问是否存在一个方案使得这些资源恰好能用完。
代码如下:
class Solution {
public:
vector<int> numOfBurgers(int t, int c) {
// 4x+2y=t, x+y=c
int x = t - 2 * c;
if (x % 2) return {};
x /= 2;
if (x < 0 || x > c) return {};
return {x, c - x};
}
};
时空复杂度 O ( 1 ) O(1) O(1)。