给出一个未排序的数字数组,其中可以有重复,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.
更多推荐
算法:找到在给定范围内的数字的计数
发布评论