Read more about . Lets discuss how it applies here:
lets says if the values are coming as 1, 2, 3 ..
on 1 then we have 1 only choice to select : 1
on 2 then out of two elements, we need to select 1, then new item should be given 1/2 chance
so any random number that comes less than or equal to 1/2 then select : 2
on 3 then out of three elements, we need to select 1, then new item should be given 1/3 chance, others will have 2/3 probability because they already exists with more probabilty
so select : 3 if random number comes between 0 < random <= 1/3
publicclassSolution {
private ListNode head;
private Random rand;
/** Note that the head is guaranteed to be not null, so it contains at least one node. */publicSolution(ListNode head) {
this.head= head;
this.rand=new Random();
}
/** Returns a random node's value. */publicintgetRandom() {
int k = 1;
ListNode node =this.head;
int res = node.val;
int i = 0;
ArrayList<Integer> reservoir =new ArrayList<Integer>();
while (i < k && node !=null) {
reservoir.add(node.val);
node = node.next;
i++;
}
i++; // i == k => i == k+1while (node !=null) {
if (rand.nextInt(i) < k) {
reservoir.set(rand.nextInt(k), node.val);
}
i++;
node = node.next;
}
return reservoir.get(0);// or return reservoir when k > 1; }
}
classSolution {
ListNode node;
publicSolution(ListNode head) {
//store the head in node node = head;
}
publicintgetRandom() {
//running index, iint count = 1;
//our selection ListNode candidate =null;
// curr assigned with the head of the node ListNode curr = node;
//loop through all the nodeswhile (curr !=null) {
//pick random and check if the value is<or<= 1/iif (Math.random()<= 1.0/ count) {
candidate = curr;
}
count += 1;
curr = curr.next;
}
return candidate.val;
}
}