找到最接近的给定数量在数组数 [英] Find the number in an array that is closest to a given number

查看:142
本文介绍了找到最接近的给定数量在数组数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数在JavaScript数组, [5,10,15,20,25,30,35] 当给定一个数x,我怎么能找到数组中的元素,是最接近这个数字?

I have an Array of integers in javascript, [5,10,15,20,25,30,35] when given a number x, how can I find the element in the array that is closest to that number?

如果数量超过了值,但低于半路下一个数字,我会选择较小的值,如果它是在中途下一个号码,我会选择较高的数字。

If the number is over a value, but less than halfway to the next number, I would choose the smaller value, if it were over halfway to the next number, I would choose the higher number.

例如7将返回5,但8将返回10.我怎样才能做到这一点?任何帮助或提示将AP preciated。我已经搜索并不能找到一个解决方案。我敢肯定,这是有点普通。

For example 7 would return 5, but 8 would return 10. How can I accomplish this? Any help or tips would be appreciated. I have searched and cannot find a solution. I'm sure this is sort of common.

推荐答案

您例如列表进行排序。如果这是总是如此,那么二进制搜索你的电话号码。如果你没有找到确切的数目,使二进制搜索通过检查各地,其中人数的将会的是,返回最接近的两个数字结束掉。小心的边缘情况下,所有的数字都大于或高于目标数都较小

Your example list is sorted. If this is always the case, then binary search for your number. If you don't find the exact number, make the binary search end off by checking the two numbers around where the number would be and return the closest. Be careful with edge cases where all numbers are greater or are all smaller than the target number

如果该列表不总是排序,然后通过数最多&所述列表保持跟踪; =目标数量和最小数> =目标数。返回一个是最接近目标。

If the list isn't always sorted, then go through the list keeping track of the largest number <= the target number and the smallest number >= the target number. Return the one that's closest to the target.

在任何一个解决方案,你需要决定是否比如你正在寻找2偏袒哪一方[1,3]。

In either solution, you'll need to decide which side to favour if for example you're searching for 2 in [1, 3].

这篇关于找到最接近的给定数量在数组数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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