-
Notifications
You must be signed in to change notification settings - Fork 43
/
linked-list-random-node.py
57 lines (48 loc) · 1.43 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
56
57
# V1 : dev
# V2
# http://bookshadow.com/weblog/2016/08/10/leetcode-linked-list-random-node/
import random
class Solution(object):
def __init__(self, head):
"""
@param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node.
:type head: ListNode
"""
self.head = head
def getRandom(self):
"""
Returns a random node's value.
:rtype: int
"""
cnt = 0
head = self.head
while head:
if random.randint(0, cnt) == 0:
ans = head.val
head = head.__next__
cnt += 1
return ans
# V3
# Time: O(n)
# Space: O(1)
from random import randint
class Solution(object):
def __init__(self, head):
"""
@param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node.
:type head: ListNode
"""
self.__head = head
# Proof of Reservoir Sampling:
# https://discuss.leetcode.com/topic/53753/brief-explanation-for-reservoir-sampling
def getRandom(self):
"""
Returns a random node's value.
: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