给定一个未排序的整数数组和2个数字i和j使得0< = i< = j< = C(常数说MAX_INTEGER)可以对其执行什么样的预处理以便您将能够在o(1)时间内找到i和j之间的数字(包括两者)。该阵列也可以有重复。
我曾想过为数组中的元素(空间o(C))构建频率数组f [] 另一个数组cf []表示累积频率(空间o(C))。
所以给定i和j,我可以查找累积频率数组并执行cf [j] - cf [i] - 这将给出i和j之间的元素数量。要包含i和j,请查找频率数组并添加值。即cf [j] - cf [i] + f [i] + f [j] 时间复杂度为o(1)* 4 =恒定时间。
通过在相应方向上找到i和j的先前非零cf数组元素,可以避免频率数组中的查找。这会增加时间复杂度,但会降低空间复杂度。
想知道这个问题是否有更好的解决方案。
注意 - 只有在完成预处理后,才能使用i和j的值。
-Vijay
答案 0 :(得分:2)
我无法想象你如何在没有使用O(C)额外空间的情况下在O(1)中这样做。
如果您只是在启动时创建数组的排序副本,则可以非常轻松地在O(log n)中进行查找。 (O(n log n))。
然后查找变为:
Binary search to find the first occurrence of i
Binary search to find the last occurrence of j
result = position_of_j - position_of_i + 1
现在,如果数组中的项目范围相对较小,则可以在O(max - min + 1)额外空间中进行,并获得O(1)查找。但最糟糕的是,(max - min + 1) == C
。
答案 1 :(得分:1)
这个怎么样,
首先,对整数数组进行排序。并为数组中的每个唯一整数创建一个哈希表,并将值作为数组中的索引,在该数组中,该整数首先出现在排序数组中,最后出现(因为可以使用dup)。哈希表的空间复杂度为O(n),访问复杂度是常量,您必须相应地为哈希表分配空间。
鉴于这些额外的数据结构,如果你想找出i和j之间的数字范围,得到i的第一个索引并从哈希表中得到j的最后一个索引,并从后者中减去第一个索引得到结果
答案 2 :(得分:-1)
Dim result() as integer
Dim C(1000) as integer
Dim Buff() as integer
Dim i as integer=50
dim j as integer=450
for count =0 to c.count-1
if c(count)>i and c(count)<j then
dim length as integer=buff.count-1
redim result(lenght+1)
for buffcount=0 to buff.count
result(buffcount)=buff(buffcount)
next
result(result.count-1)=c(count)
redim buff(result.lenght-1)
buff=result
end if
next
答案 3 :(得分:-1)
想法:
1. Binary search to find the first occurrence of i
2. Binary search to find the last occurrence of j
3. result = position_of_j - position_of_i + 1
或
1. first enter size of array
2. then enter elements of array
3. then query size
4. then enter left, right
代码链接:HackerEarth