腾讯笔试:[编程题] 有趣的数字<最简洁版> map的运用,rbegin()是最后一个值的迭代器。

[编程题] 有趣的数字
小Q今天在上厕所时想到了这个问题:有n个数,两两组成二元组,差最小的有多少对呢?差最大呢?



输入描述:

输入包含多组测试数据。 对于每组测试数据: N - 本组测试数据有n个数 a1,a2...an - 需要计算的数据 保证: 1<=N<=100000,0<=ai<=INT_MAX.



输出描述:

对于每组数据,输出两个数,第一个数表示差最小的对数,第二个数表示差最大的对数。


输入例子:
6
45 12 45 32 5 6
思路:STL map<>作为哈希是一大利器,因为它自带排序,.begin()是最小值,.rbgein()是最大值。
这道题,求最小值若是0,那就是最小的了,因为前面已经排序过了。

输出例子:
#include <iostream>  
#include <algorithm>   
#include <vector>
#include <string>  
#include <map>


using namespace std;  
  
int main()  
{  
    int n;
    while(cin>>n)  
    {
        if(n==1) {
            cout<<0<<" "<<0<<endl;
            continue;
        }
        int min_dis=0,max_dis=0;
        vector<int> vec(n,0);
        for (int i = 0; i < n; ++i) cin>>vec[i];
        sort(vec.begin(),vec.end());
        map<int,int> mp;
        map<int,int> hash;
        for (int i = 0; i < n-1; ++i)    mp[vec[i+1]-vec[i]]++;
        for (int i = 0; i < n; ++i)     hash[vec[i]]++;
        
        map<int,int>::iterator it_m=mp.begin();
        if(it_m->first==0)
        {
            for (map<int,int>::iterator it_h=hash.begin(); it_h!=hash.end(); ++it_h)
            {
                int same_count=it_h->second;
                if(same_count>1){
                    min_dis+=(same_count*(same_count-1)/2);
                }
            }
            //min_dis=max((++it_m)->second,min_dis); 真是SB,老子为什么要加这句,最小的已经是0了,还管其他的干吊?
        }else{
            min_dis=it_m->second;
        }
		if(hash.size()!=1)
        	max_dis=(hash.begin()->second)*(hash.rbegin()->second);//如果全部相同呢,不应该是Cn2吗?
        else 
            max_dis=(hash.begin()->second)*(hash.begin()->second-1)/2;

		cout<<min_dis<<" "<<max_dis<<endl;

        
 

    }  
    return 0;  
}  


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值