1. 程式人生 > >yyy loves Maths VI (mode)

yyy loves Maths VI (mode)

如果空間正常的話,可以排序,然後找n/2的位置的數

但是...

摩爾投票法,線性的時間複雜度,常量級的空間複雜度,找到陣列中出現次數大於一般的數

就是每次找到兩個不同的元素消去,直到剩下的都是同一種元素

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<cstring>
 5 #include<cmath>
 6 using namespace std;
 7 int n,x,h,cnt;
 8 int main(){
9 cin>>n; 10 for(int i=1;i<=n;i++){ 11 cin>>x; 12 if(x==h) cnt++; 13 if(!cnt) h=x,cnt=1; 14 if(x!=h) cnt--; 15 } 16 cout<<h<<endl; 17 }