【LeetCode】382. Linked List Random Node 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/linked-list-random-node/description/
题目描述
Given a singly linked list, return a random node’s value from the linked list. Each node must have the same probability of being chosen.
Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?
Example:
// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();
题目大意
随机从链表中抽出一个节点的数字。
解题方法
数组保存再随机选择
我使用一个数组保存了,然后从中间随机找的index。
代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def __init__(self, head):
"""
@param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node.
:type head: ListNode
"""
self.stack = []
while head:
self.stack.append(head.val)
head = head.next
def getRandom(self):
"""
Returns a random node's value.
:rtype: int
"""
_len = len(self.stack)
return self.stack[random.randint(0, _len - 1)]
# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()
蓄水池抽样
这个做法和398. Random Pick Index完全一致,即在一个流中随机选择一个数字。
蓄水池采样算法(Reservoir Sampling)是说在一个流中,随机选择k个数字,保证每个数字被选择的概率相等。
算法的过程:
假设数据序列的规模为 n,需要采样的数量的为 k。
首先构建一个可容纳 k 个元素的数组,将序列的前 k 个元素放入数组中。
然后从第 k+1 个元素开始,以 k/n 的概率来决定该元素是否被替换到数组中(数组中的元素被替换的概率是相同的)。 当遍历完所有元素之后,数组中剩下的元素即为所需采取的样本。
这个题中k = 1。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
Solution(ListNode* head) : h_(head) {
}
/** Returns a random node's value. */
int getRandom() {
ListNode* head = h_;
int cnt = 0, res = 0;
while (head) {
++cnt;
if (rand() % cnt == 0)
res = head->val;
head = head->next;
}
return res;
}
private:
ListNode* h_;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/
日期
2018 年 3 月 8 日
2019 年 2 月 26 日 —— 二月就要完了
【LeetCode】382. Linked List Random Node 解题报告(Python & C++)的更多相关文章
- [LeetCode] 382. Linked List Random Node 链表随机节点
Given a singly linked list, return a random node's value from the linked list. Each node must have t ...
- Leetcode 382. Linked List Random Node
本题可以用reservoir sampling来解决不明list长度的情况下平均概率选择元素的问题. 假设在[x_1,...,x_n]只选一个元素,要求每个元素被选中的概率都是1/n,但是n未知. 其 ...
- [LeetCode] 382. Linked List Random Node ☆☆☆
Given a singly linked list, return a random node's value from the linked list. Each node must have t ...
- 382 Linked List Random Node 链表随机节点
给定一个单链表,随机选择链表的一个节点,并返回相应的节点值.保证每个节点被选的概率一样.进阶:如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?示例:// 初始化一个单链表 ...
- 382. Linked List Random Node
Given a singly linked list, return a random node's value from the linked list. Each node must have t ...
- 382. Linked List Random Node(蓄水池采样)
1. 问题 给定一个单链表,随机返回一个结点,要求每个结点被选中的概率相等. 2. 思路 在一个给定长度的数组中等概率抽取一个数,可以简单用随机函数random.randint(0, n-1)得到索引 ...
- 【LeetCode】654. Maximum Binary Tree 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...
- 【LeetCode】784. Letter Case Permutation 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 循环 日期 题目地址:https://leet ...
- 【LeetCode】743. Network Delay Time 解题报告(Python)
[LeetCode]743. Network Delay Time 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: ht ...
随机推荐
- linux 线程函数小结
由于主线程已经开始跑了,次线程还在使用串口打印需要一点时间,因此打印的都是重复的. #include "pthread.h" #include "stdio.h" ...
- urllib的基本使用介绍
1. urllib中urlopen的基本使用介绍 1 ### urllib中urlopen的基本使用介绍 2 3 ## urlopen的基本用法(GET请求) 4 import urllib.requ ...
- 同一局域网,远程连接别人的Mysql数据库
数据库:MySQL 工具: Navicat, 电脑A连接电脑B的数据库, 确保两部电脑都是在同一个局域网,都是连着同一个路由器,或者连接同一个WiFi, 如果不确定是否为同一个局域网,可以打开cmd, ...
- 使用GitHub Action进行打包并自动推送至OSS
GitHub Action 是 GitHub 于 2018 年 10 月推出的一个 CI\CD 服务. 官方文档:https://docs.github.com/cn/actions CI\CD 持续 ...
- 5分钟6步强制删除kubernetes NameSpace小技巧
在使用kubernetes过程中,我们经常会遇到无法删除NameSpace的情况,但是如果一一去删除NameSpace中资源比较麻烦.下面我们给大家介绍强制删除NameSpace的方法. 一.查看已存 ...
- echo -e "\033[字背景颜色;字体颜色m字符串\033[0m
格式: echo -e "\033[字背景颜色;字体颜色m字符串\033[0m" 例如: echo -e "\033[41;36m something here \033 ...
- 【C/C++】子数组的最大累加和问题
#include <bits/stdc++.h> using namespace std; class Solution { public: /** * max sum of the su ...
- [BUUCTF]PWN——mrctf2020_easyoverflow
mrctf2020_easyoverflow 附件 步骤: 例行检查,64位程序,保护全开 本地试运行的时候就直接一个输入,然后就没了,直接用64位ida打开 只要满足18行的条件,就能够获取shel ...
- python获取命令行传参的两种种常用方法argparse解析getopt 模块解析
方法一:argparse解析 #!/usr/bin/env python3 # -*- coding:utf-8 -*- # @Time: 2020/5/20 10:38 # @Author:zhan ...
- JAVA开发 环境基础 IDEA 常用快捷键
java 源代码运行必须先用javac编译生成字节码文件 XXX.class运行 java XXX 进行运行 环境变量classpath:已编译的字节码文件搜索路径--临时配置: set classp ...