Pythonリストセットクエリ効率の比較

LeetCode 141. Linked List Cycleでは、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)

参照Icoding_F2014  結論:

単一のクエリでは、リストはO(n)のようですが、セットは重複排除されていますが、本質は赤黒木(推測、STLは赤黒木)、複雑さO(logn)、dictも同様です。 to keyハッシュが実行され、ハッシュから赤黒木が生成されて検索されます。検索の複雑さは、いわゆるO(1)ではなく、実際にはO(logn)です。O(1)は理想的な実現にすぎません。実際、多くのハッシュ実現は離散化されています。dictはsetよりも1つ多いハッシュプロセスであるため、setよりも低速ですが、違いは大きくありません。
————————————————
著作権表示:この記事は、CSDNブロガー「Icoding_F2014」の元の記事であり、CC 4.0BY-SA著作権表示に準拠しています。元のソースを添付してくださいリンクと再版のためのこのステートメント。
元のリンク:https://blog.csdn.net/jmh1996/article/details/78481365

 

PS

1.リストを使用してノードを保存します

# 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を使用してノードを保存します

# 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 

 

 

おすすめ

転載: blog.csdn.net/authorized_keys/article/details/104819202