查找数组中的众数

查找数组中出现次数最多的数

示例一

int most_(vector arr) {
	int len = arr.size();
	vector tmp(len, 0);
	vector::iterator it = arr.begin();
	while (it != arr.end()) {
		tmp[*it++]++;
	}
	return max_element(tmp.begin(), tmp.end()) - tmp.begin();
}

示例二

/*查找一个众数*/
typedef pair Int_Pair;
bool cmp_by_value(const Int_Pair& a, const Int_Pair& b) {
	return a.second < b.second;
}
int most_2(vector arr) {
	hash_map MyMap;
	hash_map::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->first;
}
/*查找出现次数最多的所有众数*/
typedef pair Int_Pair;
struct CmpByValue {
	bool operator()(const Int_Pair& a, const Int_Pair& b) {
		return a.second > b.second;
	}
};
vector most_2(vector arr) {
	hash_map MyMap;
	hash_map::iterator it1;
	for (int i = 0; i < arr.size(); i++) {
		if ((it1 = MyMap.find(arr[i])) != MyMap.end()) {
			it1->second++;
		}else {
			MyMap.insert(Int_Pair(arr[i], 1));
		}
	}
	vector vec(MyMap.begin(), MyMap.end());
	vector mostNum;
	/*自定义排序规则,按value降序*/
	sort(vec.begin(), vec.end(), CmpByValue());
	vector::iterator it2 = vec.begin();
	int maxCount = it2->second;
	for (; it2 != vec.end(); it2++) {
		if (maxCount != it2->second) break;
		mostNum.push_back(it2->first);
	}
	return mostNum;
}

你可能感兴趣的:(C/C++,C++,STL)