C++程式:尋找獨特競價遊戲中的獲勝者


假設我們有一個包含n個元素的陣列A。有n個參與者,第i個參與者選擇數字A[i]。競價遊戲的獲勝者是選擇的數字唯一且最小的參與者。我們必須找到獲勝參與者的索引。如果不可能,則返回-1。

問題類別

程式設計中的各種問題可以透過不同的技術來解決。為了解決問題,我們首先必須設計一個演算法,為此我們必須詳細研究特定問題。如果同一個問題反覆出現,可以使用遞迴方法;或者,我們也可以使用迭代結構。可以使用if-else和switch case等控制語句來控制程式中邏輯的流程。有效地使用變數和資料結構可以提供更簡單的解決方案以及輕量級、低記憶體需求的程式。我們必須檢視現有的程式設計技術,例如分治法、貪心演算法、動態規劃,並找出它們是否可行。這個問題我們可以透過一些基本的邏輯或暴力方法來解決。請遵循以下內容以更好地理解該方法。

因此,如果我們問題的輸入類似於A = [2, 3, 2, 4, 2],則輸出將為1,因為選擇了3的參與者可以贏得遊戲。

步驟

為了解決這個問題,我們將遵循以下步驟:

Define one map cnt, and another map pos, both for integer type key and integer type value
n := size of A
for initialize i := 0, when i < n, update (increase i by 1), do:
   x := A[i]
   increase cnt[x + 1] by 1
   pos[x + 1] = i
ans := -1
for each key-value pair it in cnt, do
   if value of it is same as 1, then:
      ans := pos[key of it]
      Come out from the loop
return ans

示例

讓我們看看以下實現以更好地理解:

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
   map<int, int> cnt, pos;
   int n = A.size();
   for (int i = 0; i < n; i++){
      int x = A[i];
      cnt[x + 1]++;
      pos[x + 1] = i;
   }
   int ans = -1;
   for (auto it : cnt){
      if (it.second == 1){
         ans = pos[it.first];
         break;
      }
   }
   return ans;
}
int main(){
   vector<int> A = { 2, 3, 2, 4, 2 };
   cout << solve(A) << endl;
}

輸入

{ 2, 3, 2, 4, 2 }

輸出

1

更新於:2022年4月8日

264 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告