蓄水池算法382. Linked List Random Node

来源:互联网 发布:mysql的insert into 编辑:程序博客网 时间:2024/06/09 22:12

碰到一个用到了蓄水池算法的题目:


http://blog.jobbole.com/42550/


/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    ListNode head;    Random random;    /** @param head The linked list's head.        Note that the head is guaranteed to be not null, so it contains at least one node. */    public Solution(ListNode head) {        this.head = head;               random = new Random();             }        /** Returns a random node's value. */    public int getRandom() {        ListNode curr = head;        int res = curr.val;        for (int i = 1; curr.next != null; i++) {            curr = curr.next;            if (random.nextInt(i + 1) == i)  res = curr.val;        }        return res;    }}/** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(head); * int param_1 = obj.getRandom(); */


原创粉丝点击