给定一个已排序的数字数组,如何找到小于 x 的数字的大小
可能的重复:
查找 BST 中所有小于 x 的数字 < /p>
如何我会修改二分搜索来查找排序数组中小于某个数字的数字数量吗?
Possible Duplicate:
finding all numbers less than x in a BST
How would I modify a binary search to find the number of numbers in a sorted array that are less than a certain number?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您有一个已经排序的数字数组,只需使用 binary 在排序数组中找到您的项目的插入点搜索算法。插入点的索引为您提供小于目标数量的元素数量。
在您的评论中,您提出了两个很好的问题:
为了处理这个问题,你需要继续搜索,直到找到数字应该存在的点(如果存在的话),即当前元素大于 x 且前一个元素小于 x 的索引。
为了解决这个问题,不要在第一次找到元素时停止,而是继续搜索,直到下限和上限相遇。如果您达到等于 x 的值,请按照与发现过高数字相同的方式处理它并继续平分。
If you have an already sorted array of numbers simply find the insertion point for your item in the sorted array usng a binary search algorithm. The index of the insertion point gives you the number of elements that are less than your target number.
In your comments you raised two good questions:
To handle this you keep searching until you find the point where the number should be if it were present, that is the index where the current element is greater than x and the previous element is less than x.
To handle this, instead of stopping when you first find an element, continue searching until you lower bound and upper bound meet. If you hit a value that is equal to x treat it in the same way as if you found a number that was too high and continue bisecting.
返回小于二分查找返回值的索引的所有数字。
Return all numbers less than the index of the value returned by the binary search.
查找号码并检查索引。
Find number and check index.
由于这是一个具体的数字数组,而不仅仅是可比较的对象,因此您可能需要查看插值搜索。如果数字均匀分布,则可以在 O(log log n) 时间内找到索引,而不是 O(log n)。
Since this is specifically an array of numbers and not just comparable objects, you might want to look at interpolation search. If the numbers are uniformly distributed, it can find the index in O(log log n) time instead of O(log n).
二分查找小于给定数字的最大数字。一旦你有了它的位置,这个位置也直接与你感兴趣的计数相关。
这个伪代码应该让你走上正确的轨道,但我还没有测试它。
k
= 给定数字例如:
8 11 13 20 50
、k = 19
Binary search for the largest number lower than your given number. Once you have its position, that position also directly relates to the count you're interested in.
This pseudocode should get you on the right track, but I haven't tested it.
k
= given numberFor example:
8 11 13 20 50
,k = 19