-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path382.py
85 lines (69 loc) · 2.19 KB
/
382.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
__________________________________________________________________________________________________
sample 72 ms submission
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
import random
class Solution:
def __init__(self, head: ListNode):
self.head = head
self.count = self.to_count()
"""
@param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node.
"""
def getRandom(self) -> int:
node = self.head
p = random.random()//(1/self.count)
for i in range(int(p)):
node = node.next
return node.val
"""
Returns a random node's value.
"""
def to_count(self):
node = self.head
count = 0
while node is not None:
count += 1
node = node.next
return count
# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()
__________________________________________________________________________________________________
sample 15976 kb submission
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from random import random
class Solution:
def __init__(self, head: ListNode):
"""
@param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node.
"""
self.head = head
pass
def getRandom(self) -> int:
"""
Returns a random node's value.
"""
max_p = -1
cur = self.head
res = 0
while cur:
cur_p = random()
if cur_p > max_p:
res = cur.val
max_p = cur_p
cur = cur.next
return res
# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()
__________________________________________________________________________________________________