在一個 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP