382. Linked List Random Node

本文介绍了一种称为Reservoir Sampling的算法,该算法能够在遍历整个数据集之前选取一个随机样本。文章通过数学推导解释了每个元素被选中的概率为1/n(n为数据集中元素的数量)。此外,还提供了一个C++实现示例,该示例展示了如何在一个链表中使用此算法随机选择一个节点。

应用reservior sampling ,第i个被选中的概率为1/i,之后没有被选中的概率i-1/i,所以第1个被选中的概率为1/1*(1/2)*(2/3)*...(n-1)/n=1/n,



class Solution {
public:
    /** @param head The linked list's head.
     Note that the head is guaranteed to be not null, so it contains at least one node. */

    Solution(ListNode* head) {
        p=head;
    }
    
    /** Returns a random node's value. */
    int getRandom() {
        ListNode* h=p;
        int val=h->val;
        int len=0;
        while(h)
        {
            if(rand()%(++len)==0)
                val=h->val;
            h=h->next;
        }
        return val;
    }
private:
    ListNode* p;
};


import heapq import random import sys import time class ListNode: """ Definition for singly-linked list node. """ def __init__(self, val=0, next=None): """ Initialize the node """ self.val = val self.next = next class LinkedList: """ Linked list class with minimal methods """ def __init__(self, val): """" Initialize the class @param val: the value of head node """ self.head = ListNode(val) def insert(self, val): """ Insert a vale to the head of the linked list @param val: value to be inserted into the linked list """ node = ListNode(val) node.next = self.head self.head = node def pop(self): """ Pop the head of the linked list, and return its value @return: None if head is None The val of head otherwise """ if self.head: node = self.head self.head = self.head.next return node.val def toList(self): """ Convert the linked list to a list @return: the list """ lst = [] node = self.head while (node): lst.append(node.val) node = node.next return lst def mergeKLists(lists): """" Merge K sorted linked list """ # Your code here heap = [] for i, node in enumerate(lists): if node: heapq.heappush(heap, (node.val, i, node)) dummy = ListNode(-1) curr = dummy while heap: val, i, node = heapq.heappop(heap) curr.next = node curr = curr.next if node.next: heapq.heappush(heap, (node.next.val, i,node.next)) return dummy.next if __name__ == "__main__": # We will generate 1000 lists of 1000 elements list_values = list(range(1000000)) random.shuffle(list_values) link_lists = [] K = 1000 length = len(list_values)//K for i in range(K): start, end = i*length, (i+1)*length list_values[start:end] = sorted(list_values[start:end], reverse=True) ll = LinkedList(list_values[start]) for val in list_values[start+1:end]: ll.insert(val) link_lists.append(ll) # Run your merge list algorithm here start = time.perf_counter() ans = mergeKLists(link_lists).toList() stop = time.perf_counter() # Test the result for index, val in enumerate(ans): if index != val: sys.exit("Your merge algorithm did not work.") print(f"Your algorithm passed test in time {stop-start:.5e}.")
最新发布
05-27
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值