2013 寻找主元素
暴力解法:
- 记录数组
- 用一个记录数组记录每个元素出现的次数,然后找出其中最多的次数与n/2作比较
- 枚举
- 用一个双重for循环去遍历比较
代码实现:
//记录数组
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int arr[100] = { 0 };
int arr1[100] = { 0 };
int num = 0;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
arr1[arr[i]]++;
}
int Max = -1;
for (int i = 0; i < 100; i++)
{
if (arr1[i] > Max)
{
Max = arr1[i];
num = i;
}
}
if (Max > n / 2)
cout << num;
else
cout << -1;
}
//枚举遍历
#include<iostream>
using namespace std;
int main()
{
int n;
int sum = 0;
int num = 0;
cin >> n;
int arr[100] = { 0 };
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int p = 0; p < n; p++)
{
sum = 0;
for (int k = 0; k < n; k++)
{
if (arr[p] == arr[k])
{
sum++;
num = arr[p];
}
}
if (sum > n / 2)
{
cout << num;
return 0;
}
}
cout << -1;
}