382. Linked List Random Node

382. Linked List Random Node

https://leetcode.com/problems/linked-list-random-node/

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.

Approach 1 : Reservoir Sampling

Walk through all .

For each node, if rand() % len == 0 , set the current value to the answer.

Proof:

  • For the last node n, the probability is 1n\frac{1}{n} obviously .

    So the probability of left nodes [0,n1)[0, n-1) is n1n\frac{n-1}{n}.

  • For the n-1 node, the probability is $ \frac{n-1}{n}*\frac{1}{n-1} = \frac{1}{n} $ .

    So the probability of left nodes [0,n2)[0, n-2) is n2n\frac{n-2}{n}.

  • For the n-2 node. the probability is $ \frac{n-2}{n}*\frac{1}{n-2} = \frac{1}{n} $

    So the probability of left nodes [0,n3)[0, n-3) is n3n\frac{n-3}{n}.

  • Similarly, we can prove that:

    For ANY node, the probability is 1n\frac{1}{n} .

class Solution {
public:

    ListNode* u;
    Solution(ListNode* head) {
        u = head;
    }
    dd
    int getRandom() {
        int res, len = 1;
        ListNode* v = u;
        while(v){
            if(rand() % len == 0){
                res = v->val;
            }
            len++;
            v = v->next;
        }
        return res;
    }
};

Runtime: 36 ms, faster than 87.72% of C++ online submissions for Linked List Random Node.

Memory Usage: 16.5 MB, less than 50.00% of C++ online submissions for Linked List Random Node.

Complexity Analysis

  • Time complexity : O(n)O(n)
  • Space complexity : O(1)O(1)
發佈了208 篇原創文章 · 獲贊 14 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章