求已排序数组中最长相同元素个数

来源:互联网 发布:阿尔伯特亲王知乎 编辑:程序博客网 时间:2024/04/28 23:07

已知一个已经从小到大排序的数组,这个数组中的一个平台(Plateau)就是连续的一串值相同的元素,并且这一串元素不能再延伸。例如,在1,2,2,3,3,3,4,5,5,6中1,2.2,3.3.3,4,5.5,6都是平台。是编写一个程序,接受一个数组,把这个数组中最长的平台找出来。在上面的例子中3.3.3就是该数组中最长的平台。
【说明】
这个程序十分简单,但是要编写好却不容易,因此在编写程序时应该考虑下面几点:
(4) 使用的变量越少越好;
(5) 把数组的元素每一个都只查一次就得到结果;
(6) 程序语句也要越少越好。
这个问题曾经困扰过David Gries 这位知名的计算机科学家。本题与解答取自David Gries 编写的有关程序设计的专著。
以上题目选自 冼镜光 所编《C语言名题精选百则 技巧篇》一书的第一页。书中在第98~99页给出的解答如下:


/* ------------------------------------------------------ */
/* FUNCTION longest_plateau :                             */
/*    Given a sorted (increasing) array, this function    */
/* computes the length of the longest plateau.  A plateau */
/* is a consective segment of an array with equal elements*/
/* For example, if x[] contains 1, 2, 3, 3, 4, 4, 5, 5, 5 */
/* and 6, then we have six plateaus, namely 1, 2, 3-3, 4-4  */
/* 5-5-5 and 6.  Therefore the length of the longest one   */
/* is 3.                                          */
/*    This is the simplest program which I have ever seen. */
/*                                               */
/* Copyright Ching-Kuang Shene           June/30/1989 */
/* ------------------------------------------------------ */
int longest_plateau(int x[], int n)
{
    
int  length = 1;         /* plateau length >= 1.     */
    
int  i;

    
for (i = 1; i < n; i++)
         
if (x[i] == x[i-length])
               length
++;
    
return length;
}
/* ------------------------------------------------------ */
#include 
<stdio.h>
void main(void)
{
    
int  x[] = { 3, 4, 4, 7, 8, 9, 9, 9, 9, 10};
    
int  n   = sizeof(x)/sizeof(int);
    
int  i, longest_plateau(int [], int);

     printf(
"/nLongest Plateau Computation Program");
     printf(
"/n===================================");
     printf(
"/n/nThe Given Array :");
    
for (i = 0; i < n; i++)
          printf(
"%5d", x[i]);
     printf(
"/n/nLength of the Longest Plateau is %d",
             longest_plateau(x, n));
}

原创粉丝点击