Sorting is often useful as the first step in many different tasks. The most common task is to make finding things easier, but there are other uses also.

Challenge 
Given a list of unsorted numbers, can you find the numbers that have the smallest absolute difference between them? If there are multiple pairs, find them all.

Input Format 
There will be two lines of input:

  • n - the size of the list
  • array - the n numbers of the list

Output Format 
Output the pairs of numbers with the smallest difference. If there are multiple pairs, output all of them in ascending order, all on the same line (consecutively) with just a single space between each pair of numbers. If there's a number which lies in two pair, print it two times (see sample case #3 for explanation).

Constraints 
10 <= n <= 200000 
-(107) <= x <= (107), where x ∈ array 
array[i] != array[j], 0 <= ij < N, and i != j


水题:维护一个ArrayList和记录当前最小距离的变量miniDist,每当i和i+1两个数的距离和miniDist相等时,把i放到ArrayList里面;当两个数距离小于miniDist时,把ArrayList清空,i放进去,并更新miniDist;最后根据ArrayList输出答案。

代码如下:

 import java.util.*;

 public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] ar = new int[n];
for(int i = 0;i < n;i++)
ar[i]= in.nextInt(); Arrays.sort(ar);
ArrayList<Integer> index = new ArrayList<Integer>();
int miniDis = Integer.MAX_VALUE;
for(int i = 0;i < n-1;i++){
if(ar[i+1]-ar[i] < miniDis){
index.clear();
index.add(i);
miniDis = ar[i+1]-ar[i];
}
else if(ar[i+1]-ar[i]==miniDis)
index.add(i);
}
for(int i:index){
System.out.printf("%d %d ", ar[i],ar[i+1]);
}
System.out.println(); }
}

最新文章

  1. iOS 后台处理
  2. NSArray与NSMutableArray 数组与可变数组
  3. C#变量类型
  4. 如何自定义wordpress登录界面的Logo
  5. mysql的存储过程
  6. Position a child div relative to parent container in CSS: [设置 子DIV位置 跟 父DIV相关联]
  7. zookeeper 配置详解
  8. 【转】C#程序打包安装部署之添加注册表项
  9. BZOJ3105: [cqoi2013]新Nim游戏
  10. [Ext JS 4] 实战之Grid, Tree Gird 添加按钮列
  11. Build Android-x86 ICS 4 Virtualbox from Google Virtualbox Target and Intel Kernel 编译体验
  12. MFC中实现定时执行与提醒功能(自编代码)
  13. Spring之AOP二
  14. JAVA基础-IO流(二)
  15. command not found
  16. POJ 1236 Network of Schools(tarjan)题解
  17. HDU 1061 Rightmost Digit (快速幂取模)
  18. GDB调试基础
  19. Alpha阶段第1周 Scrum立会报告+燃尽图 02
  20. python pivot() 函数

热门文章

  1. JS判断不同的浏览器,不同的浏览器版本
  2. 第二百节,jQuery EasyUI,Tabs(选项卡)组件
  3. selenium + js 处理窗口
  4. android Splashy Flash小游戏
  5. windows文件打包命令
  6. 【转】ATL提供的所有转换宏
  7. python3----连接字符串数组(join)
  8. 深入了解UIAutomation 的API
  9. eclipse下设置tomcat,修改Java代码不必重启tomcat
  10. IDEA错误的将所有代码文件都加入版本控制