查找一个阵列的两个最相似的价值观(JAVA) [英] Find the two most similar values in an array (Java)

查看:141
本文介绍了查找一个阵列的两个最相似的价值观(JAVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数数组,我想找到两个最相似的价值观(至少差)。

I have an array of integers and I want to find the two most similar values (least difference).

例如:
 如果数组中的值是 80,100,500,600,501,505 ,两个最相似的价值观是 500 501 。我怎样才能做到这一点?

Example: if the values in the array are 80,100,500,600,501,505, The two most similar values are 500 and 501. How can I do this?

推荐答案

诀窍这个问题,首先分拣阵列。这将使它所以你只需要来比较相邻的号码;选择2具有最小的区别。

The trick to this problem is sorting the array first. This will make it so you only need to compare numbers that are adjacent to each other; selecting the 2 that have the smallest difference.

伪code:

sort the array: use Arrays.sort()
 int max_difference = Integer.MAXVALUE
int val1, val2;
for(i=0; i< array_size -1; ++i) {
 int x = array[i+1] - array[i];
 if(x <= max_difference) {
   max_difference = x;
   val1 = array[i];
   val2 = array[i+1];
 }
}

在最后, VAL1 val2的将包含2最similiar值。

at the end, val1 and val2 will contain the 2 most similiar values.

这篇关于查找一个阵列的两个最相似的价值观(JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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