C++ 中的多數元素
假設我們有一個數組,我們必須檢查給定的數字 x 是否是該陣列的多數元素。該陣列是已排序的。當一個元素在陣列中出現 n/2 次時,它被稱為多數元素。比方說陣列像 {1, 2, 3, 3, 3, 3, 6},x = 3,答案為真,因為 3 是陣列的多數元素。有 4個 3。陣列的大小是 7,所以我們可以看到 4 > 7/2。
我們可以統計陣列中 x 的出現次數,如果該數字大於 n/2,則答案為真,否則為假。
示例 (C++)
#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";
}輸入
[1, 2, 3, 3, 3, 3, 6] 3
輸出
3 is the majority element of the array
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP