求已排序数组中最长相同元素个数
来源:互联网 发布:阿尔伯特亲王知乎 编辑:程序博客网 时间: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));
}
- 求已排序数组中最长相同元素个数
- 求list中,相同元素的个数
- 求数组中元素个数
- 统计一个数组中相同元素个数
- 查询数组中相同元素的个数
- oc统计数组相同元素的个数,以及数组排序
- 求两个有序数组相同元素的个数-JAVA
- C或C++ 求两个数组相同元素个数
- C或C++ 求两个数组相同元素个数
- 数组中去掉相同的元素, 排序
- 求两个相同大小已排序数组中的中位数
- 求数组中不同元素的个数
- 求数组元素个数
- 实现统计数组中相同元素个数并输出
- 统计PHP数组中相同元素的个数
- Matlab统计数组中相同元素的个数
- 输出数组中相同的元素以及个数
- 寻找数组中不相同元素的个数
- 管理软件不销售
- oracle 10g undo表空间使用率居高不下bug
- 决不放弃
- ubuntu下的一些操作
- ubuntu下java安装
- 求已排序数组中最长相同元素个数
- 菜鸟是怎样炼成的——敬给编程初学者
- GRANT /DENY/REVOKE
- ubuntu下eclipse3.3.2 无法启动解决方法
- 原来是这样
- ubuntu-Myeclipse8.0 优化
- FLASH所支持的声音格式有哪两种. 有什么特点
- IPv6技术与应用
- Extjs小结