力扣题目382:链表的随机节点。
给定一个单向链表,随即选择链表的一个节点,返回相应的节点数值,每一个节点被选中的概率一样。
实现Solution类:
链表长度10的4次方,可以初始化的时候遍历整个链表,并且把所有的链表数值预先处理到一个数组之内。
查询的时候随意选择一个数组下标,并且把数组下标对应的内容返回return。
class Solution {
List<Integer> list = new ArrayList<>();
Random random = new Random(20220116);
public Solution(ListNode head) {
while (head != null) {
list.add(head.val);
head = head.next;
}
}
public int getRandom() {
int idx = random.nextInt(list.size());
return list.get(idx);
}
}

random方法用于返回一个随机数值,随机数值范围是:0.0 <= Math.random < 1.0。
static double random()
该方法返回的是double数值:
public class Test{
public static void main(String args[]){
System.out.println( Math.random() );
System.out.println( Math.random() );
}
}