Linked List Random Node LeetCode solution in Java

1
class Solution {
2
int N = 0;
3
ListNode head = null;
4

5
public Solution(ListNode head) {
6
this.head = head;
7
}
8

9
public int getRandom() {
10
ListNode p = this.head;
11
int i = 1, ans = 0;
12
while (p != null) {
13
if (Math.random() * i < 1) ans = p.val; // replace ans with i-th node.val with probability 1/i
14
p = p.next;
15
i++;
16
}
17
return ans;
18
}
19
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0