騰訊校招筆試——小Q今天在上廁所時想到了這個問題:有n個數,兩兩組成二元組,差最小的有多少對呢?差最大呢?
阿新 • • 發佈:2019-02-18
題目:
小Q今天在上廁所時想到了這個問題:有n個數,兩兩組成二元組,差最小的有多少對呢?差最大呢?
輸入描述:
輸入包含多組測試資料。
對於每組測試資料:
N - 本組測試資料有n個數
a1,a2…an - 需要計算的資料
保證:
1<=N<=100000,0<=ai<=INT_MAX.
輸出描述:
對於每組資料,輸出兩個數,第一個數表示差最小的對數,第二個數表示差最大的對數。
輸入例子:
6
45 12 45 32 5 6
輸出例子:
解答:先sort排序一下,如果有重複的,那麼最小肯定是重複的,看有多少組。 最大肯定是最大值的個數*最小值的個數1 2
#include<bits/stdc++.h> using namespace std; int a[100005]; int b[100005]; typedef long long LL; map<int ,int > m; int main() { int n; while(~scanf("%d",&n)) { m.clear(); int j=0; int f=0; for(int i=0; i<n; i++) { scanf("%d",&a[i]); m[a[i]]++; if(m[a[i]]==1) { b[j++]=a[i]; } else { f=1; } } LL x = 0; n=j; sort(b,b+n); if(f==0) { LL Min=1e12; for(int i=1; i<n; i++) { LL num = (LL) b[i]-b[i-1]; if(num<Min) { Min=num; } } x=0; for(int i=1; i<n; i++) { LL num = (LL) b[i]-b[i-1]; if(num==Min) { x++; } } } else { x = 0; for(int i=0; i<n; i++) { if(m[b[i]]>1) { x = x + (LL)m[b[i]]*(m[b[i]]-1)/2; } } } LL y; if(n==1) { y=(LL)m[b[0]]*(m[b[0]]-1); } else { y=(LL)m[b[n-1]]*m[b[0]]; } printf("%lld %d\n",x,y); } return 0; }