-
总时间限制:
- 10000ms 内存限制:
- 4096kB
-
描述
-
一天,THU boy 小胖涛给一道题给zzh做:给你一个n个数的数列,其中某个数出现了超过n div 2次即众数,请你找出那个数。
zzh:这不是很简单吗……等等,好像有什么不对。卧槽,我好像不会做啊!
你能帮助zzh吗?
输入
-
第一行:一个正整数 n
第二行:n个小于等于2^{31}-1的正整数
输出
- 一个整数,表示你所找那个众数。 样例输入
-
7 4 1 4 2 4 3 4
样例输出
-
4
提示
-
n<=500000,数列中每一个数<=2^31-1
注意看空间限制
c++的头文件也会占用一定空间
-
-
-
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<ctime> #include<cmath> #include<string> #define N 12350 #define MAX 12345 #define MAXSUM 12500000 #define CLR(arr, what) memset(arr, what, sizeof(arr)) using namespace std; int countmax; template<class T> class Hash { private: int Key[N], Head[N], Next[N], Same[N]; int top; public: int search( int x); void push(int x); bool pre(int x); void clear(); }; template<class T> inline void Hash<T>::clear() { top = 0; CLR(Head, -1); CLR(Next, -1); CLR(Same, 0); } template<class T> inline bool Hash<T>::pre(int x) { int temp; temp = abs(x) % MAX; for(int i = Head[temp]; i != -1; i = Next[i]) //记录重复 { if(x == Key[i]) { Same[i]++; return true; } } return false; } template<class T> inline void Hash<T>::push(int x) { if(pre(x) == true) //出现过,Same记录 return ; else //没出现过 { int temp; temp = abs(x) % MAX; Key[top] = x; Next[top] = Head[temp]; Head[temp] = top; Same[top] = 1; top++; } } template<class T> inline int Hash<T>::search(int x) { int temp; temp = abs(x) % MAX; for(int i = Head[temp]; i != -1; i = Next[i]) { if(x == Key[i]) { if(Same[i]>countmax) { countmax=Same[i]; //遍历same 找最大的same } } } return countmax; // 返回最大same } int main() { int m[100005]; Hash<int> h; h.clear(); int n; cin>>n; for(int i=0;i<n;i++) { int j; cin>>j; m[i]=j; h.push(j); } //建表 for(int i=0;i<n;i++) { h.search(m[i]); } cout<<countmax; //输出最大same return 0; }