382. Linked List Random Node

Problem:

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();

思路

Solution (C++):

ListNode* u;
Solution(ListNode* head) {
    u = head;
}

/** Returns a random node's value. */
int getRandom() {
    ListNode* v = u;
    int res = v->val, len = 1;
    while (v) {
        if (rand() % len == 0) {
            res = v->val;
        }
        len++;
        v = v->next;
    }
    return res;
}

性能

Runtime: 40 ms  Memory Usage: 14 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

posted @ 2020-04-09 11:42  littledy  阅读(79)  评论(0编辑  收藏  举报