【HackerRank】Closest Numbers
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 <= i, j < N, and i != j
水题:维护一个ArrayList和记录当前最小距离的变量miniDist,每当i和i+1两个数的距离和miniDist相等时,把i放到ArrayList里面;当两个数距离小于miniDist时,把ArrayList清空,i放进去,并更新miniDist;最后根据ArrayList输出答案。
代码如下:
1 import java.util.*; 2 3 public class Solution { 4 public static void main(String[] args) { 5 Scanner in = new Scanner(System.in); 6 int n = in.nextInt(); 7 int[] ar = new int[n]; 8 for(int i = 0;i < n;i++) 9 ar[i]= in.nextInt(); 10 11 Arrays.sort(ar); 12 ArrayList<Integer> index = new ArrayList<Integer>(); 13 int miniDis = Integer.MAX_VALUE; 14 for(int i = 0;i < n-1;i++){ 15 if(ar[i+1]-ar[i] < miniDis){ 16 index.clear(); 17 index.add(i); 18 miniDis = ar[i+1]-ar[i]; 19 } 20 else if(ar[i+1]-ar[i]==miniDis) 21 index.add(i); 22 } 23 for(int i:index){ 24 System.out.printf("%d %d ", ar[i],ar[i+1]); 25 } 26 System.out.println(); 27 28 } 29 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了