C ++中的多数元素
假设我们有一个数组;我们必须检查给定的数字x是否是该数组的多数元素。数组已排序。当一个元素在数组中出现n/2次时,该元素被称为多数元素。假设一个数组像{1,2,3,3,3,3,6},x=3,这里的答案是正确的,因为3是数组的多数元素。有四个3。数组的大小为7,因此我们可以看到4>7/2。
我们可以计算x在数组中的出现次数,如果数字大于n/2,则答案为true,否则为false。
范例(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
热门推荐
7 祝福语简短七夕
10 双十一祝福语大全简短
11 苦难的成语祝福语简短
12 祝女儿出嫁简短祝福语
13 中秋祝福语简短版大全
14 小朋友祝福语简短的话
15 老婆生日祝福语简短孩子
16 迟到的过年祝福语简短
17 恩师退休花束祝福语简短
18 小孩想说的祝福语简短