【每日一题】不浪费原料的汉堡制作方案

文章目录

Tag

【解方程】【2023-12-25】


题目来源

1276. 不浪费原料的汉堡制作方案


解题思路

方法一:解方程

思路

这是一个简单的解决二元一次方程的问题。

根据题意有以下关系式:

{ t o t a l _ j u m b o × 4 + t o t a l _ s m a l l × 2 = t o m a t o S l i c e s t o t a l _ j u m b o + t o t a l _ s m a l l = c h e e s S l i c e s \left\{ \begin{array}{c} total\_jumbo\times 4+\ total\_small\times 2=tomatoSlices\\ total\_jumbo+total\_small=cheesSlices\\ \end{array} \right. {total_jumbo×4+ total_small×2=tomatoSlicestotal_jumbo+total_small=cheesSlices

通过简单的消元可得:

{ t o t a l _ j u m b o = 1 2 × t o m a t o S l i c e s − c h e e s e S l i c e s t o t a l _ s m a l l = 2 × c h e e s e S l i c e s − 1 2 × t o m a t o S l i c e s \left\{ \begin{array}{c} total\_jumbo=\frac{1}{2}\times tomatoSlices-cheeseSlices\\ total\_small=2\times cheeseSlices-\frac{1}{2}\times tomatoSlices\\ \end{array} \right. {total_jumbo=21×tomatoSlices−cheeseSlicestotal_small=2×cheeseSlices−21×tomatoSlices

根据题意, t o t a l _ j u m b o , t o t a l _ s m a l l ≥ 0 total\_jumbo, total\_small≥0 total_jumbo,total_small≥0 且 x , y ∈ N x, y \in \mathbb{N} x,y∈N,因此需要满足:

{ t o m a t o S l i c e s = 2 k , k ∈ N 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 4 × c h e e s e S l i c e s ≥ t o m a t o S l i c e s \left\{ \begin{array}{c} tomatoSlices=2k,\ k\in \mathbb{N}\\ tomatoSlices\ge 2\times cheeseSlices\\ 4\times cheeseSlices\ge tomatoSlices\\ \end{array} \right. ⎩ ⎨ ⎧tomatoSlices=2k, k∈NtomatoSlices≥2×cheeseSlices4×cheeseSlices≥tomatoSlices

若不满足,则无解。

算法

cpp 复制代码
class Solution {
public:
    vector<int> numOfBurgers(int tomatoSlices, int cheeseSlices) {
        if (tomatoSlices % 2 || tomatoSlices < cheeseSlices * 2 || cheeseSlices * 4 <tomatoSlices) {
            return {};
        }
        return {tomatoSlices / 2 - cheeseSlices, cheeseSlices * 2 - tomatoSlices / 2};
    }
};

复杂度分析

时间复杂度: O ( 1 ) O(1) O(1)。

空间复杂度: O ( 1 ) O(1) O(1)。


写在最后

如果您发现文章有任何错误或者对文章有任何疑问,欢迎私信博主或者在评论区指出 💬💬💬。

如果大家有更优的时间、空间复杂度的方法,欢迎评论区交流。

最后,感谢您的阅读,如果有所收获的话可以给我点一个 👍 哦。

相关推荐
CC.GG1 小时前
【C++】哈希表的实现
java·c++·散列表
bkspiderx2 小时前
C++变量生命周期:从创建到销毁的完整旅程
c++·生命周期·作用域·变量生命周期
T0uken3 小时前
现代 C++ 项目的 CMake 工程组织
c++
H CHY4 小时前
C++代码
c语言·开发语言·数据结构·c++·算法·青少年编程
xiaolang_8616_wjl4 小时前
c++题目_传桶(改编于atcoder(题目:Heavy Buckets))
数据结构·c++·算法
小小8程序员4 小时前
除了 gcc/g++,还有哪些常用的 C/C++ 编译器?
c语言·开发语言·c++
希望_睿智5 小时前
实战设计模式之中介者模式
c++·设计模式·架构
博语小屋6 小时前
转义字符.
c语言·c++
Lhan.zzZ6 小时前
Qt跨线程网络通信:QSocketNotifier警告及解决
开发语言·c++·qt
Aevget6 小时前
QtitanDocking 如何重塑制造业桌面应用?多视图协同与专业界面布局实践
c++·qt·界面控件·ui开发·qtitandocking