【发布时间】:2014-12-17 05:45:25
【问题描述】:
我想确定在我的每个给定区间(很多)中有多少个输入数组(最多 50000 个)。
目前,我正在尝试用这个算法来做,但是太慢了:
示例数组:{-3, 10, 5, 4, -999999, 999999, 6000}
示例间隔:[0, 11](含)
- 排序数组 -
O(n * log(n))。 (-999999, -3, 4, 5, 10, 6000, 999999) - 查找 min_index:
array[min_index] >= 0-O(n)。 (例如,min_index == 2)。 - 查找 max_index:
array[max_index] <= 11-O(n)。 (例如,max_index == 4)。 - 如果两个索引都存在,则
Result == right_index - left_index + 1(例如,Result = (4 - 2 + 1) = 3)。
【问题讨论】:
-
为什么不直接把数组从头到尾遍历一遍,直接计数呢? O(n)
-
@Deduplicator,我有很多间隔。
-
当数组排序后,你可能会在对数时间内得到
min_index。 -
@Jarod42:仍然受排序约束。
-
数组元素的最大值和最小值是多少?
标签: c++ arrays algorithm sorting search