寻找多数元素 算法

来源:互联网 发布:淘宝txt下载 编辑:程序博客网 时间:2024/05/10 09:42

定义: 

整型数组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;elsereturn 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;elsemajority = n/2;if (count > majority)return c;elsereturn -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();}


原创粉丝点击