📅  最后修改于: 2023-12-03 15:27:10.174000             🧑  作者: Mango
这是一段Javascript程序,用于从单链表中选择随机节点。输入为链表头节点,输出为随机选中的节点。
function getRandomNode(head) {
let node = head;
let count = 1;
while (node) {
if (Math.random() < 1 / count) {
return node;
}
node = node.next;
count++;
}
return head;
}
程序采用了蓄水池抽样算法,具体步骤如下:
蓄水池抽样算法的核心思想是:当当前遍历到第i个节点时,以1/i的概率选择该节点,同时以1-1/i的概率选择前i-1个节点中的任意一个。由于每个节点被选中的概率相等,因此最终的结果是均匀且随机的。
假设我们有以下链表:
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
const head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
如果我们要从该链表中选择一个随机节点,只需要调用getRandomNode函数:
const randomNode = getRandomNode(head);
console.log(randomNode.val); // 输出随机选中的节点的值
其中,randomNode就是随机选中的节点。由于该算法的时间复杂度为O(n),与链表长度无关,因此适用于任何长度的链表。