找出数组中元素之间的最小差异 [英] Finding out the minimum difference between elements in an array

查看:114
本文介绍了找出数组中元素之间的最小差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数数组,带有有限数量的值。我的工作是找到数组中任何两个元素之间的最小差。

I have an integer array with some finite number of values. My job is to find the minimum difference between any two elements in the array.

考虑到数组包含

4, 9, 1, 32, 13

在4和1之间的差异最小,因此答案是3。

Here the difference is minimum between 4 and 1 and so answer is 3.

解决此问题的算法应该是什么。另外,我不知道为什么,但是我觉得使用树木可以相对容易地解决这个问题。可以做到吗?

What should be the algorithm to approach this problem. Also, I don't know why but I feel that using trees, this problem can be solved relatively easier. Can that be done?

推荐答案

最小差异将是按顺序排列的连续对之间的差异之一。对数组进行排序,然后遍历成对的相邻数字以寻找最小的差异:

The minimum difference will be one of the differences from among the consecutive pairs in sorted order. Sort the array, and go through the pairs of adjacent numbers looking for the smallest difference:

int[] a = new int[] {4, 9, 1, 32, 13};
Arrays.sort(a);
int minDiff = a[1]-a[0];
for (int i = 2 ; i != a.length ; i++) {
    minDiff = Math.min(minDiff, a[i]-a[i-1]);
}
System.out.println(minDiff);

此打印 3

这篇关于找出数组中元素之间的最小差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆