一.题目描述:给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 【n/2】的元素。你可以假设数组是非空的,并且给定的数组总是存在众数。
二.解题思路:
1.第一组数据:1,2,2,2,2,1 n=6 众数为2;
2.第二组数据:1,3,3 n=3 众数为3;
3.第三组数据:1,3,3 ,4,4,5,5,5,5,5,5 n=11 众数为5;
总结规律可以发现:若数组中的数据经过排序后, 那么众数就是数组中位于n/2处的元素。
三.代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution
{
public:
int majorityElement(vector<int>& nums)
{
int n=nums.size();
sort(nums.begin(),nums.end());
int result;
result=nums[n/2];
return result;
}
};
int main()
{
int a[5]={1,2,3,2,2};
vector<int>b(a,a+5);
Solution solve;
cout<<solve.majorityElement(b)<<endl;
return 0;
}
版权声明:本文为weixin_40260504原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。