383.leetcode题目讲解(Python):链表随机节点(Linked List Random Node)

题目

题目

解题思路

这道题比较简单,将链表结点的值逐一放入一个列表中,然后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----苔原带

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容