# 0382. Linked List Random Node ###### tags: `Leetcode` `Medium` `Reservoir Sampling` Link: https://leetcode.com/problems/linked-list-random-node/ ## 思路 Reservoir Sampling ## Code ```java= class Solution { private ListNode head; private ListNode curr; Random rand; public Solution(ListNode head) { this.head = head; this.curr = head; rand = new Random(); } public int getRandom() { this.curr = head; int cnt = 0; int idx = 0; while(curr != null){ cnt++; if(rand.nextInt(cnt)==0){ idx = curr.val; } curr = curr.next; } return idx; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up