春节期间小明使用微信收到很多个红包,非常开心。在查看领取红包记录时发现,某个红包金额出现的次数超过了红包总数的一半。请帮小明找到该红包金额。写出具体算法思路和代码实现,要求算法尽可能高效。
给定一个红包的金额数组gifts及它的大小n,请返回所求红包的金额。
若没有金额超过总数的一半,返回0。
测试样例:
[1,2,3,2,2],5
返回:2
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
class Gift {
public:
int getValue(vector<int> gifts, const int n) {
// write code here
sort(gifts.begin(), gifts.end());//先进行排序
int count = 0;//记录次数count
for (int i = 0; i < n; i++){
//红包金额的数目超过红包的一半,那么这个数字一定在和中位数相等
if (gifts[i] == gifts[n/2])//如果和排序后的中位数相等,count++
count++;
}
if (count > (n/2))//n/2代表红包个数的一半,如果count大于数目一半
return gifts[n/2];//返回这个金额
return 0;//否则返回0
}
};
int main()
{
Gift gf;
vector<int> v({ 1, 2, 3, 2, 2 });
int ret=gf.getValue(v, 5);
cout << ret << endl;
system("pause");
return 0;
}