使用O(logN)时间复杂度

时间:2016-11-15 20:03:18

标签: algorithm sorting data-structures hashmap binary-search

你能否在时间复杂度为O(logN)的节点(对象)的有序链表上进行二进制搜索?我知道链接列表不支持直接索引,因此您无法执行list [3]或list.get(3)之类的操作,因此基本上您需要遍历列表中的所有元素找到中间元素的索引。但是,如果你有一个额外的数据结构,如HashMap(key = index,value = node),该怎么办?这可行吗?

示例: 我们说我们有这个清单:

1 -> 4 -> 7 -> 9 -> 14 -> 18

HashMap用于获取O(1)中的节点:

0 -> 1
1 -> 4
2 -> 7
3 -> 9
4 -> 14
5 -> 18

现在,如果我们想找到14,我们会这样做:

binarySearch(0,5) : middle = 2 -> get node 7 from the Hashmap. 14 > 7 so ->
binarySearch(3,5) : middle = 4 -> get node 14 from the Hashmap. 14 == 14 ->Voila

当然,要构建这个hashmap,你必须做N个操作,所以O(N)的时间复杂度,但是如果你已经有了HashMap,这可以吗?

如果是,您是否可以使用此方法在带有附加HashMap的链接列表上以O(nlogn)时间复杂度进行插入排序?

基本上:

 1. for each element ( O(n) )
    2. find the position of the element in the list in O(logN) with binary search that uses the Hashmap to get the element at the middle position in O(1).
    3. insert the element in the Linked List in O(1)
    4. insert the (index,element) into the Hashmap in O(1)

O(nlogn)时间复杂度。或者我在做/假设有什么问题?

1 个答案:

答案 0 :(得分:0)

这个想法非常好,以下是如何使其工作:作为密钥,您可以使用节点的值。如果列表节点值是唯一的,则可以使用节点作为哈希映射的值(否则为节点列表)。因此,您仍然可以像往常一样在列表中从节点到节点,但您也可以通过O(1)中的值进行访问。

如果值在插入和删除时发生更改,则必须更新哈希映射,但所有内容都是O(1)或O(c),其中c是列表中重复值的最大数量,如果c没有' t取决于n然后即使重复也是O(1),否则为O(n)。