我如何找到最近的数组元素为任意(非会员)的数量? [英] How do I find the closest array element to an arbitrary (non-member) number?

查看:182
本文介绍了我如何找到最近的数组元素为任意(非会员)的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看似类似的问题:查找在数组(在Java中)和找到最接近的匹配双打的阵列(实际上是一个地理问题)。



我有双打的(排序)数组。给出的任意数量(其可以是或可以不是对于阵列元件中的一个完全匹配),我怎样才能返回它是最接近的匹配



<数的索引p>例如,使用下面的数组:




  • 1.8

  • 2.4

  • 2.7

  • 3.1

  • 4.5



查询2.5将与一个索引1返回,对应于2.4的值。



,用于检测完全位于的范围之外的值,奖励积分数组元素。例如,使用上面列出的阵列,代码可以决定,4.6是在,但5.9是出来。如果你想尝试的问题的一部分,具体是在你的手中。


解决方案

Array.BinarySearch ,它返回:




指定数组中指定的值的索引,如果值被找到。如果没有找到值和值是在阵列小于一个或多个元素,一个负数这是比值大的第一个元素的索引的按位求补。如果没有找到值和值大于任何在数组中的元素的更大,负数它是按位补码(最后一个元素的索引加1)。




现在,不会让你100%的方式存在,因为你知道电话号码或者是小于或大于比赛更大,但它真的只给你留下两个指数检查


Seemingly similar questions: "Finding closest number in an array" (in Java) and "find nearest match to array of doubles" (actually a geography problem).

I have a (sorted) array of doubles. Given an arbitrary number (which may or may not be an exact match for one of the array elements), how can I return the index of the number which is the closest match?

For example, using the following array:

  • 1.8
  • 2.4
  • 2.7
  • 3.1
  • 4.5

Querying 2.5 would return with an index of 1, corresponding to the value of 2.4.

Bonus points for detecting values that lie completely outside of the range of the array elements. For example, using the array listed above, your code may decide that 4.6 is in, but 5.9 is out. If you want to try this part of the question, the specifics are in your hands.

解决方案

Array.BinarySearch, which returns:

The index of the specified value in the specified array, if value is found. If value is not found and value is less than one or more elements in array, a negative number which is the bitwise complement of the index of the first element that is larger than value. If value is not found and value is greater than any of the elements in array, a negative number which is the bitwise complement of (the index of the last element plus 1).

Now that won't get you 100% of the way there, since you'll know the number is either less than or greater than the match, but it really only leaves you with two indices to check.

这篇关于我如何找到最近的数组元素为任意(非会员)的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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