众数问题
2012-04-01 03:10
211 查看
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
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的时候,是无效的。
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的时候,是无效的。