C++中第一個唯一數字


假設我們有一個整數佇列,我們需要檢索該佇列中的第一個唯一整數。我們必須實現一個名為FirstUnique的類:它將由佇列中的數字初始化。定義一個函式showFirstUnique(),它將返回佇列中第一個唯一整數的值,如果不存在這樣的整數則返回-1。另一個方法是add(value),它將值插入到佇列中。

所以,如果輸入是這樣的

  • 用[2,3,4]初始化,然後按如下方式呼叫函式:

  • showFirstUnique()

  • add(5)

  • showFirstUnique()

  • add(2)

  • showFirstUnique()

  • add(3)

  • showFirstUnique()

那麼輸出將分別是2、2、3、-1。

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

  • 定義一個佇列q

  • 定義一個對映cnt

  • 初始化器將接收陣列

    • 對於nums中的每個元素i

      • (將cnt[i]增加1)

    • 對於nums中的每個元素i

      • 如果cnt[i]等於1,則:

        • 將i插入到q中

  • 定義一個函式showFirstUnique()

  • 當(q不為空且cnt[q的第一個元素] > 1)時,執行:

    • 從q中刪除元素

  • 返回(如果q為空,則返回-1,否則返回q的第一個元素)

  • 定義一個函式add(),它將接收值,

  • (將cnt[value]增加1)

  • 如果cnt[value]等於1,則:

    • 將value插入到q中

示例

讓我們看看下面的實現,以便更好地理解:

線上演示

#include <bits/stdc++.h>
using namespace std;
class FirstUnique {
public:
   queue <int> q;
   map <int, int> cnt;
   FirstUnique(vector<int>& nums) {
      for (int i : nums) {
         cnt[i]++;
      }
      for (int i : nums) {
         if (cnt[i] == 1) {
            q.push(i);
         }
      }
   }
   int showFirstUnique() {
      while (!q.empty() && cnt[q.front()] > 1) q.pop();
         return q.empty() ? -1 : q.front();
   }
   void add(int value) {
      cnt[value]++;
      if (cnt[value] == 1)
         q.push(value);
   }
};
main(){
   vector<int> v = {2,3,5};
   FirstUnique ob(v);
   cout << (ob.showFirstUnique()) << endl;
   ob.add(5);
   cout << (ob.showFirstUnique()) << endl;
   ob.add(2);
   cout << (ob.showFirstUnique()) << endl;
   ob.add(3);
   cout << (ob.showFirstUnique()) << endl;
}

輸入

{2,3,5}
ob.showFirstUnique();
ob.add(5);
ob.showFirstUnique();
ob.add(2);
ob.showFirstUnique();
ob.add(3);
ob.showFirstUnique();

輸出

2
2
3
-1

更新於:2020年11月17日

484 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告