给一个单向链表,随机选择一个node in one pass

来源:互联网 发布:电脑ps软件 编辑:程序博客网 时间:2024/04/28 00:04
public class ReserviorSampling {    public ListNode sampling(ListNode head){        ListNode s = head;        Random rand = new Random();        int count = 1;        while(head != null){            int position = (int) (rand.nextInt(count) + 1);            count++;            if(position == 1)                s = head;        }        return s;    }}

这个题可以有变种。

当要随机选择k个时。

public class ReserviorSampling {    public ListNode sampling(ListNode head){        Queue<ListNode> q = new Queue<ListNode>;        Random rand = new Random();        int count = 1;        while(head != null){            int position = (int) (rand.nextInt(count) + 1);            count++;            if(position <= k)            {if(q.size() == k)q.pop(); q.push(head);}        }        return s;    }}