數組中出現次數超過一半數組

在這裏插入圖片描述

這個題不難

一般大家上來想到的都是 for 循環 把每個數字的次數都統計一遍
然後還要for循環找到出現最多的次數
然後用這個次數對比數組大小
最後根據這個次數 在去找這個數字是幾

我一想這個實現太麻煩了 stl 爲什麼不用呢?

直接 sort 排序
count 計算每個出現的數字
然後結果

看代碼

int MoreThanHalfNum_Solution(vector<int> numbers) {

	if (numbers.empty())
		return 0;

	sort(numbers.begin(), numbers.end());

	int times = -1;
	int max_ = -1;
	int index = -1;
	for (auto i = 0; i < numbers.size(); i++)
	{
		times = count(numbers.begin(), numbers.end(), numbers.at(i));

		if (times > max_)
		{
			max_ = times;
			index = i;
		}	
	}

	if (max_ > numbers.size() / 2)
		return numbers[index];
	else
		return 0;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章