2:找众数

总时间限制: 
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;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值