算法复习 - 递归求解众数问题(分治)

题目描述:
在这里插入图片描述
解析:
通过分治,每次求解s[mid]的出现次数,然后统计。将s拆分成两个部分,然后再分别求解。

代码:

#include
#include
#include

using std::cin;
using std::cout;
using std::endl;
using std::vector;


void search(const vector<int>& s, int low, int high, int &mid, int& left, int& right)
{
     
	mid = (high + low)/2;
	for (left = low; left <= high; left++)
		if (s[left] == s[mid])break;
	for (right = left + 1; right <= high; right++)
		if (s[right] != s[mid])break;
	right--;
}

void findMode(const vector<int>&s, int low, int high, int &cnt, int &maxTimeNum)
{
     
	
	if (low <= high)
	{
     
		int left, right, mid;
		search(s, low, high, mid, left, right);
		if (cnt <= right - left + 1)
		{
     
			cnt = right - left + 1;
			maxTimeNum = s[mid];
		}
		findMode(s, low, left - 1, cnt, maxTimeNum);
		findMode(s, right + 1, high, cnt, maxTimeNum);
	}
}

int main()
{
     
	vector<int>S = {
      1, 2, 2, 2, 3, 3, 6, 6, 6 };
	int low = 0, high = S.size() - 1;
	int maxTime = 0;
	int maxTimeNum = 0;
	findMode(S, low, high, maxTime, maxTimeNum);
	cout << "重数是"<<maxTime <<endl<<"众数是:"<< maxTimeNum << endl;
	return 0;
}

你可能感兴趣的:(算法作业,算法)