[腾讯校招] 有趣的数字

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

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

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

输入例子:
6
45 12 45 32 5 6

输出例子:
1 2

#include <iostream>
#include <cstdio>
#include <vector>
#include <map>
#include <algorithm>
#include <set>
using namespace std;

void work(vector<int> &myArray, int n) {
        map<int, int> cnt;
        set<int> mySet;
        sort(myArray.begin(), myArray.end());
        int element;
        for(int i = 0; i < n; i++) {
                element = myArray[i];
                if(!cnt.count(element)) {
                        cnt[element] = 1;
                } else {
                        cnt[element]++;
                }
                mySet.insert(element);
        }
        int maxValue;
        if(myArray[0] != myArray[n-1]){
                maxValue = cnt[myArray[0]] * cnt[myArray[n-1]];
        } else {
                maxValue = 0;
        }

        bool isExitZero = false;
        vector<int> value;
        int v;
        for(int i = 1; i < n; i++) {
                v = myArray[i] - myArray[i-1];
                value.push_back(v);
                if(v == 0) {
                        isExitZero = true;
                        break;
                }
        }
        sort(value.begin(), value.end());
        int  minValue = 0;
        if(isExitZero) {
                int u;
                for(set<int>::iterator it = mySet.begin(); it != mySet.end(); it++) {
                         u = *it;
                         if(cnt[u] >= 2) {
                                minValue += (cnt[u] * (cnt[u] - 1))/2;
                         }
                }
        } else {
                int x = value[0];
                for(int i = 0; i < n-1; i++) {
                        if(value[i] == x){
                                minValue++;
                        }
                        else {
                                break;
                        }
                }
        }
        printf("%d %d\n", minValue, maxValue);

}


int main()
{
    int n, read;
    vector<int> myArray;
    while(scanf("%d", &n) != EOF) {
        myArray.clear();
        for(int i = 0; i < n; i++) {
                scanf("%d", &read);
                myArray.push_back(read);
        }
        if(n == 1) {
        printf("0 0\n");
        } else {
                work(myArray, n);
        }
    }

    return 0;
}


/**
4
2 2 2 2
5
4 5 6 7 8
6
1 2 2 2 3 3
8
2 2 1 1 3 3 4 4
6
45 12 45 32 5 6
**/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值