众数问题

来源:互联网 发布:知乎 江歌 贫困生 编辑:程序博客网 时间:2024/04/23 19:31
How to find if a number is present >= (n / 2) times in an array of size
n? 

关于这个题目,有没有时间复杂度是O(n),空间复杂度是O(1)的解?


solution by swanswan @ MitBBS

int number=a[0];int count=1;for (int i=1; i<n; i++) {if (a[i]!=number) {   count--;   if (count==0) {      number = a[i];      count = 1;   }} else count++;}return number;

Simple modification is to add another loop to check if there's a number 
which has appeared [n/2] times.
【 在 iverson1407 (iverson1407) 的大作中提到: 】
: 这个只对绝对众数有效。也就是大于n/2的时候,但是等于n/2的时候,是无效的。

原创粉丝点击