在LeetCode 141. Linked List Cycle中,分别使用list和set存储node,遍历时间差别巨大。
因此,做测试对比list和set的查询效率。
import time
import numpy as np
nums = np.random.randint( 0, 1e7, int(1e3))
set1 = set(np.random.randint(0, 1e7, int(1e5)))
list1 = list(set1)
t1 = time.time()
for i in nums:
i in set1
t2 = time.time()
for i in nums:
i in list1
t3 = time.time()
print(t2-t1)
print(t3-t2)
单次查询中:看来list 就是O(n)的;而set做了去重,本质应该一颗红黑树(猜测,STL就是红黑树),复杂度O(logn);dict类似对key进行了hash,然后再对hash生成一个红黑树进行查找,其查找复杂其实是O(logn),并不是所谓的O(1)。O(1)只是理想的实现,实际上很多hash的实现是进行了离散化的。dict比set多了一步hash的过程,so 它比set慢,不过差别不大。
————————————————
版权声明:本文为CSDN博主「Icoding_F2014」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/jmh1996/article/details/78481365
PS
1. 用list存储node
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
nodes = []
while head != None:
if head in nodes:
return True
else:
nodes.append(head)
head = head.next
return False
2. 用set存储node
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
# set要比list的遍历速度快
nodes = set()
while head != None:
if head in nodes:
return True
else:
nodes.add(head)
head = head.next
return False