#include"pch.h"
#include<iostream>
#include<string.h>
using namespace std;
//时间复杂度为o(n),空间复杂度o(1)
int MainElement(int A[], int n) {
//求主元素,出现次数大于一半
//思路:1.count<0重新开始计数,找出最后大于0的主元素
int count = 1,i;
int key = A[0];
for ( i = 1; i < n; i++) {//找主元素
if (A[i] == key) count++;
else {
if (count == 0) {
key = A[i]; count = 1;//重新计数
}
else count--;
}
}
//2.判断是否为真的主元素
if (count > 0) {
for (i = count = 0; i < n; i++) {
if (A[i] == key)
count++;
}
}
if (count > n / 2) return key;
else return -1;
}
int main() {
int n;
cout << "数组的长度:" << endl;
cin >> n;
int*A = new int[n];
memset(A, 0, sizeof(int)*n);//可以全部初始化为0
cout << "输入值" << endl;
for(int i=0;i<n;i++) {
cout << "数字:" << endl;
cin >> A[i];
}
/*for (int i = 0; i < n; i++) {
cout << "数字:" << endl;
cout<< A[i]<<endl;
}*/
if(MainElement(A, n)!=-1)
cout<<"主元素是"<<MainElement(A, n)<<endl;
else cout << "不存在主元素" << endl;
}