候选人算法

现在有一个整数数组,已知一个数出现的次数超过了一半,请用O(n)的复杂度的算法找出这个数

#include <stdio.h>

int main(int argc, char **argv)
{
	int i, candidate, vote;
	int a[10]={1,2,3,1,2,1,1,6,1,1}; 

	candidate = 1<<31;
	vote = 0;
	for (i = 0; i < 10; i++) {
		if (a[i] != candidate) {
			if (vote == 0) {	/* 废掉candidate, 把a[i]作为新的候选人 */
				candidate = a[i];
				vote = 1;
			}
			else {			/* 候选人的票减1 */
				vote--;
			}
		}
		else {				/* 候选人的票加1 */
			vote++;
		}
	}
	// 最后剩下的候选人即为出现次数超过一半的数
	printf("candidate = %d, vote = %d\n", candidate, vote);

	return 0;
}

 

posted on 2014-11-11 19:43  kangbry  阅读(857)  评论(0编辑  收藏  举报

导航