当前位置:网站首页>7/13 (pond sampling)
7/13 (pond sampling)
2022-07-28 15:19:00 【Dream fish YX】
1, subject
Power button
https://leetcode.cn/problems/linked-list-random-node/
2, Problem solving
class Solution {
private int count=0;
private ListNode head;
private Random r =new Random();
// Record the length of header node and linked list
public Solution(ListNode head) {
this.head=head;
while(head !=null){
count++;
head=head.next;
}
}
// utilize Random Of nextInt() Get random integers , And find the corresponding node
public int getRandom() {
ListNode node=head;
for(int i=r.nextInt(count);i>0;i--){
node=node.next;
}
return node.val;
}
}// Pool sampling ( Suppose there are n Number )( For a large number of data streams of unknown length )
// Choose a number at random : When I meet the i Element time , Should have 1/i The probability of selecting the element ,1-1/i The probability of keeping the original choice .( Judge whether the random number is 0)
// prove :P choice = The first i The product of the selection probability of an element and the original selection probability of its subsequent elements =1/n( There are many options for the front elements , Not easy to calculate )
// For example, select the first element probability :1*P( Since then, keep the original choice )=1/n
// Random selection k Number : In the i Elements are placed in k/i The probability of selecting the element , With 1-k/i Keep the original choice ( By judging whether the random number is less than k)
class Solution {
private ListNode head;
private Random r=new Random();
public Solution(ListNode head) {
this.head=head;
}
public int getRandom() {
int answer=0;
ListNode node=head;
for(int i=0;node!=null;node=node.next){
if(r.nextInt(i+1)==0){
answer=node.val;
// The first element must be selected , But whether the answer will change after that is uncertain , namely answer It must be assigned .
}
i++;
}
return answer;
}
}3, Run a screenshot


边栏推荐
猜你喜欢

Have you ever used the single merchant mall, which is smooth enough to make people feel numb?

听说crmeb多商户增加了种草功能?

JS学习笔记18-23

电压继电器DY-28C

svg 验证码识别体验

day 7/12

The second 1024, come on!

crmeb 标准版window+phpstudy8安装教程(二)

How Charles installs and uses

Apple iPhone app icon hidden how to retrieve and restore the hidden app icon displayed on the iPhone iPhone desktop to the iPhone iPhone iPhone desktop?
随机推荐
Mysql易错知识点整理(待更新)
redis常用命令总结(自备)
电压继电器DY-28C
解决pycharm使用powershell出错问题
Jwy-32b voltage relay
crmeb pro2.2即将增加的功能都有哪些?
4518. Minimum ticket price
Crmeb knowledge paid manual installation tutorial
Drawing method using GL under URP
封装统一返回对象MessageResult
JY-7GA/1电压继电器
JS学习笔记24-28:结束
Pyinstaller packages py as an EXE file
拓展运算符是深拷贝还是浅拷贝
mysql 8.0常用(持续更新)
PMP [agile textbook + full truth simulation question]. After the exam on June 25, agile has become the top priority
4518. 最低票价
crmeb 标准版Window+phpstudy8安装教程(一)
SRTT-110VDC-4H-C时间继电器
Is the expansion operator a deep copy or a shallow copy