查找数组中出现次数最多的数
示例一
int most_(vector<int> arr) {
int len = arr.size();
vector<int> tmp(len, 0);
vector<int>::iterator it = arr.begin();
while (it != arr.end()) {
tmp[*it++]++;
}
return max_element(tmp.begin(), tmp.end()) - tmp.begin();
}
示例二
/*查找一个众数*/
typedef pair<int, int> Int_Pair;
bool cmp_by_value(const Int_Pair& a, const Int_Pair& b) {
return a.second < b.second;
}
int most_2(vector<int> arr) {
hash_map<int, int> MyMap;
hash_map<int, int>::iterator it1;
for (int i = 0; i < arr.size(); i++) {
/*如果key已存在, 则将出现次数加一*/
if ((it1 = MyMap.find(arr[i])) != MyMap.end()) {
it1->second++;
}else {
/*如果key不存在,则入map,出现次数为1*/
MyMap.insert(Int_Pair(arr[i], 1));
}
}
it1 = max_element(MyMap.begin(), MyMap.end(), cmp_by_value);
return it1->