您的位置:首页 > 编程语言

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

2017-03-08 19:00 225 查看
[编程题] 有趣的数字

小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;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: