C++ 中無浪費食材的漢堡數量


假設我們有兩個整數 tomatoSlices 和 cheeseSlices。以下為不同漢堡的配料 -

  • 巨無霸:4 片番茄和 1 片乳酪。
  • 小漢堡:2 片番茄和 1 片乳酪。

我們必須找到 [total_jumbo, total_small],以便剩餘的番茄片數為 0,剩餘的乳酪片數也為 0。如果無法使剩餘的番茄片和乳酪片等於 0,則返回 []。因此,如果輸入為 tomatoSlices = 16 和 chesseSlices = 7,則輸出將為 [1, 6]。這表示要製作一個巨無霸和 6 個小漢堡,我們需要 4*1 + 2*6 = 16 片番茄和 1 + 6 = 7 片乳酪。

為解決此問題,我們將按以下步驟進行 -

  • 建立一個名為 ans 的陣列
  • 如果番茄為奇數或乳酪 > 番茄/2 或番茄 > 4*乳酪,則返回 ans
  • x := (4 * 乳酪 - 番茄) / 2
  • y := (番茄 - (2*x)) / 4
  • 將 y 再將 x 插入到陣列 ans
  • 返回 ans

為了更好地理解,讓我們來看以下實現 -

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector<int> numOfBurgers(int t, int c) {
      vector <int> ans;
      if(t % 2 != 0 || c > t/2 || t > c*4)return ans;
      int x = (4 * c - t) / 2;
      int y = ( t - (2 * x) )/ 4;
      ans.push_back(y);
      ans.push_back(x);
      return ans;
   }
};
main(){
   Solution ob;
   print_vector(ob.numOfBurgers(16,7));
}

輸入

16
7

輸出

[1, 6, ]

更新時間:02-May-2020

253 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.