在一個 C++ 排序陣列中檢查多數元素


假設我們有一個數組;我們必須檢查給定的數字 x 是否為該陣列的多數元素。該陣列是已排序的。當一個元素在陣列中出現 n/2 次時,它被稱為多數元素。假設一個數組如下所示:{1, 2, 3, 3, 3, 3, 6},x = 3,這裡答案為 true,因為 3 是陣列的多數元素。有四個 3。陣列的大小是 7,所以我們可以看到 4 > 7/2。

我們可以計算 x 在陣列中出現的次數,如果該數字大於 n/2,那麼答案將為 true,否則為 false。

例如

 現場演示

#include <iostream>
#include <stack>
using namespace std;
bool isMajorityElement(int arr[], int n, int x){
   int freq = 0;
   for(int i = 0; i<n; i++){
      if(arr[i] == x )
         freq++;
      if(arr[i] > x)
         break;
   }
   return (freq > n/2);
}
int main() {
   int arr[] = {1, 2, 3, 3, 3, 3, 6};
   int n = sizeof(arr)/sizeof(arr[0]);
   int x = 3;
   if (isMajorityElement(arr, n, x))
      cout << x << " is the majority element of the array";
   else
      cout << x << " is not the majority element of the array";
}

輸出

3 is the majority element of the array

更新於:21-10-2019

148 次瀏覽

職業起步

透過完成課程獲得認證

開始
廣告
© . All rights reserved.