寻找数组中的多项元素有多种办法,直接暴力循环或者是先排序后寻找中间元素最坏的时间复杂度为nlogn。几天记录一个使用候选者的方法去寻找数组中的多项元素时间复杂度则为n+n即为n
与直接遍历循环查找最大的不同点是,寻找候选者的过程中我们定义一个count值,当遍历时数组值与我们的候选值相等时count++,如果不同则count–,这将缩短我们的遍历程度,无需从头遍历到尾部。在一个数组内部删除两个不相同的数则原序列中的多数元素依旧是新数组中的多数元素。
值得强调的是一个数是最后的候选数不代表是多项数,多项数的意思是个数超过n/2的数(n表示数组长度),12233则2和3都不是多项数所以最后需要遍历一次计算求出来的候选数是否大与n/2;
#include<stdio.h>
int A[8]={0,1,3,3,5,3,5,3};
int n=7;
int candidate(int m)
{
int j=m,c=A[m],count=1;
while(j<n&&count>0)
{ j=j+1;
if(c==A[j])count++;//通过计数可以提前完成遍历;
else count--;
}
if(j==n)return c;
else return candidate(m+1);
}
int majority()
{
int c=candidate(1);
int count=0;
//遍历完成候选数的计算 如果大与n/2则为多项数
for(int i=0;i<=n;i++)
{
if(c==A[i])
count++;
}
if(count>n/2)
return c;
else return -1;
}
int main()
{
int c = majority();
if(c!=-1)
printf("%d",c);
else
printf("none");
return 0;
}