題目
解題思路
這道題比較簡單,將鏈表結點的值逐一放入一個列表中,然後random一個返回值。
參考代碼 (beats 99%)
'''
@auther: Jedi.L
@Date: Fri, May 10, 2019 10:52
@Email: [email protected]
@Blog: www.tundrazone.com
'''
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
self.candid = []
while self.head:
self.candid.append(self.head.val)
self.head = self.head.next
def getRandom(self) -> int:
"""
Returns a random node's value.
"""
return random.choice(self.candid)
如何刷題 : Leetcode 題目的正確打開方式
我的GitHub : GitHub
其他題目答案:leetcode題目答案講解彙總(Python版 持續更新)
其他好東西: MyBlog----苔原帶