最长平台

问题:已知一个已经从小到大排序的数组,这个数组中的一个平台就是连续的一串值相同的元素,并且这一串元素不能再延伸。如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/archive/2012/09/11/2680393.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值