在C ++中检查排序数组中的多数元素
假设我们有一个数组;我们必须检查给定的数字x是否是该数组的多数元素。数组已排序。当一个元素在数组中出现n/2次时,它被称为多数元素。假设一个数组像{1,2,3,3,3,3,6},x=3,这里的答案是正确的,因为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
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志