2:找众数
總時間限制:?10000ms? 內存限制:?4096kB
描述 輸入第一行:一個正整數 n
第二行:n個小于等于2^{31}-1的正整數 輸出一個整數,表示你所找那個眾數。 樣例輸入 7
4 1 4 2 4 3 4 樣例輸出 4 提示n<=500000,數列中每一個數<=2^31-1
注意看空間限制
#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; //輸出最大samereturn 0;}
一天,THU boy 小胖濤給一道題給zzh做:給你一個n個數的數列,其中某個數出現了超過n div 2次即眾數,請你找出那個數。
zzh:這不是很簡單嗎……等等,好像有什么不對。臥槽,我好像不會做啊!
你能幫助zzh嗎?
第二行:n個小于等于2^{31}-1的正整數
注意看空間限制
c++的頭文件也會占用一定空間
總結
- 上一篇: 03:Poor Herobrine 直接
- 下一篇: HDU 1879(最小生成树问题,Pri