当前位置:网站首页>Leetcode-382. random nodes of linked list
Leetcode-382. random nodes of linked list
2022-07-24 03:24:00 【KGundam】
Mathematical problems - Random and sampling
Topic details
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 .
Ideas :
Unlike arrays , Before traversing the linked list , We cannot know the total length of the linked list . Here we can use reservoir mining
sample : Traverse the list once , After traversing to the m When a node , Yes 1/m The probability of selecting this node overrides the previous node selection .
Simple proof :
My code :
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */
class Solution
{
ListNode* h;
public:
Solution(ListNode* head) :h(head) {
} // Use the header node with h Save it
int getRandom()
{
int ans = h->val; // initialization ans Is the head node val
ListNode* node = h->next; // utilize node Go back and forth
int i = 2; // Because at this time node It's No 2 Nodes , therefore i Initialize to 2
while (node) // Traverse to the end
{
// Randomly generate one [0,i) The random number , If it is 0,
// Just change the answer to the number of nodes (1/i Probability )
if ((rand() % i) == 0)
ans = node->val;
// Otherwise, continue to traverse the node backwards
++i;
node = node->next;
}
return ans;
}
};
/** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(head); * int param_1 = obj->getRandom(); */
边栏推荐
- How to implement desktop lyrics in pyqt
- C user defined type details
- Is the reverse repurchase of treasury bonds safe? How to open an account online?
- B. Eastern Exhibition- Codeforces Round #703 (Div. 2)
- Interviewer: if the order is not paid within 30 minutes after it is generated, it will be automatically cancelled. How to realize it?
- 移动通信的新定义:R&SCMX500 将提高5G设备的IP数据吞吐量
- How to write selenium's testng.xml
- Huawei then responded to the rumor of "cleaning up employees over the age of 34". How can programmers cope with the "35 year old crisis"?
- Binary search
- 俄罗斯方块、1
猜你喜欢

OSPF comprehensive experimental configuration

Emqx v4.4.5 Publishing: new exclusive subscriptions and mqtt 5.0 publishing attribute support

Xiaodi and Xiaohui

SolidWorks cannot reference references

Do you know how to do interface testing well?
![Embedded system transplantation [5] - Cross compilation tool chain](/img/2a/eadaaafe794aa9b3106441fa50ffc7.png)
Embedded system transplantation [5] - Cross compilation tool chain

Lagrange polynomial

正则表达式 \b \B 深入浅出理解单词边界的匹配

IDEA Clone的项目报Cannot resolve symbol ‘Override‘

Talk about the application of FIFO
随机推荐
The new idea 2022.2 was officially released, and the new features are nice
QT custom class uses custom parametric signals and slots
08 reptile project
Keras deep learning practice (15) -- realize Yolo target detection from scratch
B. Eastern Exhibition- Codeforces Round #703 (Div. 2)
Industrial controller, do you really know your five insurances and one fund?
C language implementation of user login program
正則錶達式 \b \B 深入淺出理解單詞邊界的匹配
Ue5 split screen (small map) solution
New definition of mobile communication: R & scmx500 will improve the IP data throughput of 5g devices
Lagrange polynomial
How to realize WiFi Internet short message authentication in the park / factory
How to realize software function safety
Using global data to realize data sharing in wechat applet
Hcip day 10 (initial BGP border gateway protocol)
Basic syntax of MySQL DDL and DML and DQL
Advantages, disadvantages and summary of sequence list and linked list
Bingbing learning notes: basic operation of vim tool
4.合宙Air32F103_LCD
Binary search