找出元件之间的最小差在一个阵列

编程入门 行业动态 更新时间:2024-10-10 14:27:48
本文介绍了找出元件之间的最小差在一个阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 。

更多推荐

找出元件之间的最小差在一个阵列

本文发布于:2023-11-29 06:21:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645592.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:阵列   元件   最小

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!