Table of Content
题目

解题思路
这道题比较简单,将链表结点的值逐一放入一个列表中,然后random一个返回值。
参考代码 (beats 99%)
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 |
''' @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) |