LeetCode 1276. 不浪费原料的汉堡制作方案:鸡兔同笼解方程

2023-12-25 13:29:42

【LetMeFly】1276.不浪费原料的汉堡制作方案:鸡兔同笼解方程

力扣题目链接:https://leetcode.cn/problems/number-of-burgers-with-no-waste-of-ingredients/

圣诞活动预热开始啦,汉堡店推出了全新的汉堡套餐。为了避免浪费原料,请你帮他们制定合适的制作计划。

给你两个整数?tomatoSlices?和?cheeseSlices,分别表示番茄片和奶酪片的数目。不同汉堡的原料搭配如下:

  • 巨无霸汉堡:4 片番茄和 1 片奶酪
  • 小皇堡:2 片番茄和?1 片奶酪

请你以?[total_jumbo, total_small]([巨无霸汉堡总数,小皇堡总数])的格式返回恰当的制作方案,使得剩下的番茄片?tomatoSlices?和奶酪片?cheeseSlices?的数量都是?0

如果无法使剩下的番茄片?tomatoSlices?和奶酪片?cheeseSlices?的数量为?0,就请返回?[]

?

示例 1:

输入:tomatoSlices = 16, cheeseSlices = 7
输出:[1,6]
解释:制作 1 个巨无霸汉堡和 6 个小皇堡需要 4*1 + 2*6 = 16 片番茄和 1 + 6 = 7 片奶酪。不会剩下原料。

示例 2:

输入:tomatoSlices = 17, cheeseSlices = 4
输出:[]
解释:只制作小皇堡和巨无霸汉堡无法用光全部原料。

示例 3:

输入:tomatoSlices = 4, cheeseSlices = 17
输出:[]
解释:制作 1 个巨无霸汉堡会剩下 16 片奶酪,制作 2 个小皇堡会剩下 15 片奶酪。

示例 4:

输入:tomatoSlices = 0, cheeseSlices = 0
输出:[0,0]

示例 5:

输入:tomatoSlices = 2, cheeseSlices = 1
输出:[0,1]

?

提示:

  • 0 <= tomatoSlices <= 10^7
  • 0 <= cheeseSlices <= 10^7

方法一:鸡兔同笼解方程

这道题可以概况为:

一只鸡1头2腿,一只兔1头4腿。共有c头t腿,问鸡兔各几何?

解法很简单,一个二元一次方程:

设x鸡y兔,则有:

  • 4 x + 2 y = t 4x + 2y = t 4x+2y=t,
  • x + y = c x + y = c x+y=c

于是有: 2 x + 2 y = 2 c 2x + 2y = 2c 2x+2y=2c

所以: x = 0.5 t ? c x = 0.5t - c x=0.5t?c, y = c ? x = 2 c ? 0.5 t y = c - x = 2c - 0.5t y=c?x=2c?0.5t

因为鸡兔不能为负数且不能为半数,所以要满足 x > = 0 x>=0 x>=0 y > = 0 y>=0 y>=0 4 x + 2 y = t 4x+2y=t 4x+2y=t(其中 x = ? 0.5 t ? c ? x = \lfloor 0.5t-c\rfloor x=?0.5t?c?

  • 时间复杂度 O ( 1 ) O(1) O(1)
  • 空间复杂度 O ( 1 ) O(1) O(1)

AC代码

C++
class Solution {
public:
    vector<int> numOfBurgers(int tomatoSlices, int cheeseSlices) {
        int x = 0.5 * tomatoSlices - cheeseSlices, y = cheeseSlices - x;
        if (x < 0 || y < 0 || 4 * x + 2 * y != tomatoSlices) {
            return {};
        }
        return {x, y};
    }
};
Python
# from typing import List

class Solution:
    def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]:
        x, y = int(0.5 * tomatoSlices - cheeseSlices), int(2 * cheeseSlices - 0.5 * tomatoSlices)
        if x < 0 or y < 0 or 4 * x + 2 * y != tomatoSlices:
            return []
        return [x, y]

同步发文于CSDN,原创不易,转载经作者同意后请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/135196793

文章来源:https://blog.csdn.net/Tisfy/article/details/135196793
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。