最长平台

问题:已知一个已经从小到大排序的数组,这个数组中的一个平台就是连续的一串值相同的元素,并且这一串元素不能再延伸。如1,2,2,3,3,3,4,5,5,6中1,2,2,3,3,4,5,5,6都是平台。

分析:

此问题可归结为查找问题,数组内容已经排序完毕,查找相同元素个数最多的元素。

关键问题是如何确定最长的相同元素。

#include <iostream>
#include <ctime>
#include <vector>
#include <algorithm>
using namespace std;

void RandomInitArray(int *arr,int arrLenth,int minValue=0,int maxValue=10)
{
srand(time(NULL));

int elapse = maxValue - minValue;

for (int i=0;i<arrLenth;++i)
{
arr[i] = rand()%elapse+minValue;
}
}

void OutputArray(int *arr,int arrLen)
{
for (int i=0;i<arrLen;++i)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}

//求最长平台
void MaxPlateau(int *arr,int arrLen)
{
int maxLen = 1;
int maxEle = arr[0];

for (int i=1;i<arrLen;++i)
{
if (arr[i] == arr[i-maxLen])
{
++maxLen;
maxEle = arr[i];
}
}

cout<<"序列中最长平台元素是:"<<maxEle<<endl;
cout<<"最长平台长度是:"<<maxLen<<endl;
}

int main()
{
int arrLen = 10;
vector<int> arr(arrLen);

//随机初始化数组
RandomInitArray(&arr[0],arrLen);
//打印当前数组内容
cout<<"当前数组内容是:"<<endl;
OutputArray(&arr[0],arrLen);
//排序
sort(arr.begin(),arr.end());
cout<<"排序后数组内容是:"<<endl;
OutputArray(&arr[0],arrLen);
//求出最长平台
MaxPlateau(&arr[0],arrLen);

return 0;
}

image

原文地址:https://www.cnblogs.com/sharpfeng/p/2680393.html