分析
重点是时间复杂度只能在O(n)内;
代码
#include <stdio.h>
int FindMostApperse(int *num,int len){
int candicate = 0;
int count = 0;
for(int i = 0;i<len;i++)
{
if(count == 0)
{
candidate = num[i];
count = 1;
}
else
{
if(candidate == num[i])
count++;
else
count--;
}
}
return candidate;
}
int main()
{
int arr[] = {2,1,2,1,1,2,3,1,1};
int len = sizeof(arr)/sizeof(arr[0]);
printf("%d\n",FindMostApperse(arr,len)); //1
return 0;
}
方法2 Hash法