-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathlinked-list-random-node.py
55 lines (42 loc) · 1.19 KB
/
linked-list-random-node.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Time: ctor: O(1)
# getRandom: O(n)
# Space: O(1)
from random import randint
# if the length is unknown without using extra space
class Solution(object):
def __init__(self, head):
"""
:type head: Optional[ListNode]
"""
self.__head = head
# Proof of Reservoir Sampling:
# https://discuss.leetcode.com/topic/53753/brief-explanation-for-reservoir-sampling
def getRandom(self):
"""
:rtype: int
"""
reservoir = -1
curr, n = self.__head, 0
while curr:
reservoir = curr.val if randint(1, n+1) == 1 else reservoir
curr, n = curr.next, n+1
return reservoir
# Time: ctor: O(n)
# getRandom: O(1)
# Space: O(n)
from random import randint
# if the length is known with using extra space
class Solution2(object):
def __init__(self, head):
"""
:type head: Optional[ListNode]
"""
self.__lookup = []
while head:
self.__lookup.append(head.val)
head = head.next
def getRandom(self):
"""
:rtype: int
"""
return self.__lookup[randint(0, len(self.__lookup)-1)]