算法:找到在给定范围内的数字的计数

编程入门 行业动态 更新时间:2024-10-25 06:23:59
本文介绍了算法:找到在给定范围内的数字的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出一个未排序的数字数组,其中可以有重复,pre-过程中的阵列,这样找到一个给定的范围内数字的计数,时间是O(1)。

given an unsorted number array where there can be duplicates, pre-process the array so that to find the count of numbers within a given range, the time is O(1).

例如, 7,2,3,2,4,1,4,6 。 = 2 和< = 5 是 5 。 (2,2,3,4,4)。

For example, 7,2,3,2,4,1,4,6. The count of numbers both >= 2 and <= 5 is 5. (2,2,3,4,4).

推荐答案

排序数组。对于排序后的数组中的每个元素中,插入元件到一个哈希表,与元件作为密钥的值,并且其阵列作为相关值中的位置。被跳过任何价值,你需要插入为好。

Sort the array. For each element in the sorted array, insert that element into a hash table, with the value of the element as the key, and its position in the array as the associated value. Any values that are skipped, you'll need to insert as well.

要找到的范围内的项目数,查找值的位置在哈希表中的范围内的每一端,并减去从上下找到该范围的大小。

To find the number of items in a range, look up the position of the value at each end of the range in the hash table, and subtract the lower from the upper to find the size of the range.

更多推荐

算法:找到在给定范围内的数字的计数

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

发布评论

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

>www.elefans.com

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