题目
题目解题思路
这道题比较简单,将链表结点的值逐一放入一个列表中,然后random一个返回值。
参考代码 (beats 99%)
'''
@auther: Jedi.L
@Date: Fri, May 10, 2019 10:52
@Email: xiangyangan@gmail.com
@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----苔原带
网友评论