找出元件之间的最小差在一个阵列 [英] Finding out the minimum difference between elements in an arrays

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

问题描述

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

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天全站免登陆