腾讯2017暑假实习生编程题有趣的数字

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


输入描述:

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



输出描述:

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


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

输出例子:
1 2
 
 
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
 
public class Main {
 
     public static void main(String[] args) {
         Scanner sc =  new Scanner(System.in);
         while (sc.hasNext()) {
             // 1、输入数组元素,并排序
             int n = sc.nextInt();
             int [] nums =  new int [n];
             for ( int i =  0 ; i < n; i++) {
                 nums[i] = sc.nextInt();
             }
             Arrays.sort(nums);
             
             // 2、寻找差的绝对值的最小值,同时统计最小值、最大值的个数
             int c1 =  0 ;
             int c2 =  1 ;
             int min = Integer.MAX_VALUE;
             HashMap<Integer, Integer> dif =  new HashMap<Integer, Integer>();
             for ( int i =  0 ; i < nums.length -  1 ; i++) {
                 min = Math.min(min, nums[i +  1 ] - nums[i]);
                 if (nums[i] == nums[ 0 ])
                     c1++;
                 if (nums[i] == nums[nums.length -  1 ])
                     c2++;
                 if (dif.get(nums[i +  1 ] - nums[i]) !=  null ) {
                     dif.put(nums[i +  1 ] - nums[i], dif.get(nums[i +  1 ] - nums[i]) +  1 );
                 else {
                     dif.put(nums[i +  1 ] - nums[i],  1 );
                 }
             }
 
             // 3、计算差的绝对值最小的对数
             int minCount =  0 ;
             if (min ==  0 ) {  // 数组中有等值段
                 int label = nums[ 0 ];
                 int count =  1 ;
                 for ( int i =  1 ; i < nums.length; i++) {
                     if (nums[i] == label) {
                         count++;
                     else {
                         label = nums[i];
                         minCount += (count * (count -  1 )) /  2 ;
                         count =  1 ;
                     }
                 }
                 minCount += (count * (count -  1 )) /  2 ;
             else // 数组中没有等值段
                 minCount = dif.get(min);
             }
 
             // 4、计算差的绝对值最大的对数
             int maxCount =  0 ;
             if (nums[nums.length -  1 ] - nums[ 0 ] ==  0 // 等值数组
                 maxCount = n * (n -  1 ) /  2 ;
             else
                 maxCount = c1 * c2;
             
             // 5、输出结果
             System.out.println(minCount +  " " + maxCount);
         }
     }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值