当前位置:网站首页>Notes on random nodes of force buckle 382 linked list
Notes on random nodes of force buckle 382 linked list
2022-07-19 14:45:00 【Thunder little GABA】
Power button 382 Random node of linked list
I'll give you a single linked list , Randomly select a node in the linked list , And return the corresponding node value . Every node The probability of being selected is the same .
Realization Solution class :
Solution(ListNode head) Initializing objects with an array of integers .
int getRandom() Randomly select a node from the linked list and return the value of the node . All nodes in the linked list have the same probability of being selected .
Example :

Input
["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
[[[1, 2, 3]], [], [], [], [], []]
Output
[null, 1, 3, 2, 2, 3]
explain
Solution solution = new Solution([1, 2, 3]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() Method should return randomly 1、2、3 One of them , The probability of each element being returned is equal .
source : Power button (LeetCode)
link :https://leetcode.cn/problems/linked-list-random-node
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
Random sampling is required in the linked list and the probability of each element being returned is equal , You can't simply use random numbers , I haven't thought about it for a long time , After referring to the official solution , I know a method that I can understand better , Since random numbers cannot be used directly , Then it can be converted into an array of random numbers to store the data , So the probability of each element is the same , Don't worry about probability , Results can be obtained by direct sampling .
class Solution { List<Integer> list;// Define a integer Type of list( Nodes must be integers , It's directly used here integer type ) Random random;// Define a random The random number public Solution(ListNode head) { list = new ArrayList<Integer>(); while (head != null) { list.add(head.val); head = head.next; }// stay list Add the values of the incoming linked list nodes in turn , random = new Random(); } public int getRandom() { return list.get(random.nextInt(list.size())); // obtain list Random numbers within the number of elements and as list Index to get randomly generated elements } }
The second official pond sampling method is difficult for me to understand , It involves spatial complexity and mathematical logic .
Need to spend O(n) Space to store all the elements in the linked list , Can we do it O(1) The spatial complexity of ?
From the head of the chain , Traverse the entire list , On the second page traversed i Nodes , Randomly selected interval [0,i) An integer in , If it is equal to 0, Then set the answer to the node value , Otherwise, the answer remains the same .
The algorithm will ensure that the probability that the value of each node becomes the last returned value is 1/n, Prove the following :
In the interval [0,i) Internal selection 0, That is to say 1/i The possibility of selecting , In fact, the probability of each node is equal , Is to change a way of thinking to solve , Official code :
class Solution { ListNode head; Random random; public Solution(ListNode head) { this.head = head; random = new Random(); } public int getRandom() { int i = 1, ans = 0; for (ListNode node = head; node != null; node = node.next) { if (random.nextInt(i) == 0) { // 1/i Probability selection ( Replace with the answer ) ans = node.val; } ++i; // There are just a few nodes i } return ans; } }
边栏推荐
- Colliding mice collision engineering analysis
- Huawei wireless device configuration intelligent roaming
- Display module in pyGame
- 深入理解事务隔离级别
- Huawei wireless device configuration user CAC
- Mvcc multi version concurrency control
- The bill module of freeswitch
- Dr. Tao's lunar line reverses by 6.0
- Sliding window maximum problem
- TDesign 在 vitest 的实践
猜你喜欢

44、使用OrienMask进行实例分割目标检测,并进行mnn部署和ncnn部署

Configure spectrum navigation for Huawei wireless devices

Colliding Mice碰撞老鼠工程分析

Redis源码与设计剖析 -- 1.简单动态字符串

Redis source code and design analysis -- 1 Simple dynamic string

Win10 Microsoft Store打不开(开启TLS 1.2)

手册不全,如何手工刨出TongWeb的监控信息?

ShanDong Multi-University Training #3
![[mqtt from getting started to improving series | 06] subscribe subscription workflow of mqtt3.1.1](/img/bf/9f8d8b2a73406970941fce33d3e754.png)
[mqtt from getting started to improving series | 06] subscribe subscription workflow of mqtt3.1.1

The first step of agile: turn "iteration" into "sprint" and start!
随机推荐
OSPF appendix anti ring Reissue
MySQL read / write separation
The manual is not complete. How to manually dig out the monitoring information of tongweb?
Use of token in ogg
SQL related time date type
P8346 the clearest air and sea [undirected graph topology]
[Luogu p3220] and not (construction) (digit DP) (inference)
【MQTT从入门到提高系列 | 07】MQTT3.1.1之链路保活及断开
优秀的jar包启动shell脚本收藏
Redis source code and design analysis -- 1 Simple dynamic string
Huawei wireless device configuration user CAC
Opencv template
MySQL index (II)
Analysis of network communication flow of different containers on the same host
ClassNotFoundException:com.tongweb.geronimo.osgi.locator.ProviderLocator
The first step of agile: turn "iteration" into "sprint" and start!
Optimal Biking Strategy【DP + 二分】
Sliding window maximum problem
MySQL view
树与二分图【思维】
