算法:找到在给定范围内的数字的计数 [英] algorithm: find count of numbers within a given range

查看:111
本文介绍了算法:找到在给定范围内的数字的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个未排序的数字数组,其中可以有重复,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 &GT的计数code>。 (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.

这篇关于算法:找到在给定范围内的数字的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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