问题:已知一个已经从小到大排序好的数组,说这个数组中的一个平台,就是连续的一串值相同的元素,并且这一串元素不能再延伸。例如,在1,2,2,3,3,3,4,5,5,6中1,2.2,3.3.3,4,5.5,6都是平台。试编写一个程序,接收一个数组,把这个数组中的最长平台找出来。
以下是我的解法:
int longest_plateau(int array[],int n)
{
int maxLength = 1;
int tmpLength = 1;
int initNum = array[0];
for(int i = 0; i < n; i++)
{
if(array[i]==initNum)
{
tmpLength++;
}
else
{
if(maxLength < tmpLength )
{
maxLength = tmpLength;
tmpLength = 1;
}
else
{
tmpLength = 1;
}
initNum = array[i];
}
}
return maxLength;
}
大师David Greis的代码:
int longest_plateau2(int x[], int n)
{
int length = 1;
int i;
for(i = 1;i < n; i++)
{
if(a[i]==a[i-length])
length++;
}
return length++;
}
但是,如果当数组不是按照顺序排列好的话,下面的这个解法就会出错。
906

被折叠的 条评论
为什么被折叠?



