/*已知一个整数序列A=(a0,a1,..,an-1),其中0<=ai<n(0<=i<n)。若存在ap1=ap2=...=apm=x且m>n/2
(0<=pk<n,1<=k<=m),则称x为A的主元素。例如A=(0,5,5,3,5,7,5,5),则5为主元素;有如A=(0,5,5,3,5,1,5,7),则
A中没有主元素。假设A中的n个元素保存在一个一维数组中,请设计一个尽可能高效的算法,找出A的主元素。若
存在主元素,则输出该元素,否则输出-1*/
#include<stdio.h>
#include<stdlib.h>
#define InitSize 10
typedef int ElemType;
typedef struct{
ElemType *data;
int length;
}SqList;
bool InitList(SqList &L)
{
L.data = (ElemType*)malloc(sizeof(ElemType)*InitSize);
L.length = 0;
return true;
}
bool findDominant(SqList L,ElemType &dom)
{
ElemType c;
int count;
c = L.data[0];
count = 1;
for(int i=0;i<L.length;++i)
{
if(L.data[i] == c)
++count;
else{
if(count>0)
--count;
else
{
c = L.data[i];
count=1;
}
}
}
if(count>0)
for(i=count=0;i<L.length;++i)
if(L.data[i] == c)
++count;
if(count>L.length/2)
dom = c;
else
dom = -1;
return true;
}
bool printList(SqList L)
{
for(int i=0;i<L.length;++i)
printf("%d ",L.data[i]);
printf("\n");
return true;
}
void main()
{
ElemType dom;
SqList L;
InitList(L);
int a[8] = {0,5,5,3,5,7,5,5};
for(int i=0;i<8;++i)
{
L.data[i] = a[i];
++L.length;
}
printList(L);
findDominant(L,dom);
printf("%d\n",dom);
}
顺序表-查找主元素
最新推荐文章于 2024-08-17 12:40:50 发布
这篇博客介绍了一种高效算法,用于在整数序列中查找主元素,即出现次数超过序列一半的元素。文章通过C语言实现了一个简单的线性扫描方法,并给出了示例代码来演示如何找到序列的主元素。如果不存在主元素,则返回-1。
660

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



