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

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;
    }
}

你可能感兴趣的:(给一个单向链表,随机选择一个node in one pass)