[LeetCode] 382. Linked List Random Node ☆☆☆

时间:2021-04-08 07:18:20

 

Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.

Follow up:

What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?

Example:

// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();

 

解法: 

  由于无法确定链表的长度,或者链表的长度很长,因此需要采用水塘抽样算法。由于限定了head一定存在,所以我们先让返回值res等于head的节点值,然后让curr指向head的下一个节点,定义一个变量count,初始化为1,若curr不为空我们开始循环,我们在[0, count)中取一个随机数,如果取出来0,那么我们更新res为当前的curr的节点值,然后此时count自增一,curr指向其下一个位置,这里其实相当于我们维护了一个大小为1的水塘,然后我们随机数生成为0的话,我们交换水塘中的值和当前遍历到底值,这样可以保证每个数字的概率相等,参见代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    private ListNode head;

    /** @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;
    }
    
    /** Returns a random node's value. */
    public int getRandom() {
        int count = 1;
        int res = head.val;
        ListNode curr = head.next;
        while (curr != null) {
            if (new Random().nextInt(++count) == 0) {
                res = curr.val;
            }
            curr = curr.next;
        }
        return res;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(head);
 * int param_1 = obj.getRandom();
 */