您的位置:首页 > 其它

寻找多数元素 算法

2012-04-20 19:29 627 查看
定义:

整型数组a[1...n],如果整数x在数组a中出现的次数多于半数,则x称为多数元素

应用概念:

观察结论5.1:在原序列中去除两个不同的元素后,那么在原序列中的多数元素在新序列中还是多数元素。

例1: 1,2,2,3,2,2,3 显然2是多数元素

去除1,2,在2,3,2,2,3中2仍是多数元素

去除1,3,在2,3,2,2,3中2更是多数元素

例2: 1,3,2,3,2,2,3 显然没有多数元素

去除1,3,在2,3,2,2,3中2成了多数

测试代码:

#include <stdio.h>

int candidate(int a[], int m, int n)
{
int j = m, c = a[m], count = 1;

while (j < n && count > 0)
{
++ j;
if (a[j] == c)
++ count;
else
-- count;
}

if (j == n)
return c;
else
return candidate(a, j+1, n);
};

// a[1...n]
int Majority(int a[], int n)
{
int c = candidate(a, 1, 10);
int count = 0;
int majority;

for (int i = 1; i <= n; ++ i)
if (a[i] == c)
++ count;

if (n%2 == 0)
majority = n/2 + 1;
else
majority = n/2;
if (count > majority)
return c;
else
return -1;
};

int main()
{
int a[11];

for (int i = 1; i < 11; ++ i)
scanf("%d",a+i);

printf("%d\n",Majority(a, 10));
getchar();
getchar();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: