[LeetCode] 382. Linked List Random Node 鏈表隨機節點

來源:互聯網
上載者:User

標籤:ram   @param   記憶體   length   display   blank   演算法   while   int   

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

 

給一個鏈表,隨機返回一個節點。

解法1:先統計出鏈表的長度,然後根據長度隨機產生一個位置,然後從開頭遍曆到這個位置。但如果n很大就不好處理了。

解法2: 水塘抽樣 Reservoir sampling,是一系列的隨機演算法,其目的在於從包含n個項目的集合S中選取k個樣本,其中n為一很大或未知的數量,尤其適用於不能把所有n個項目都存放到記憶體的情況。

Java:

public class Solution {        ListNode head;    Random random;        public Solution(ListNode h) {        head = h;               random = new Random();            }        public int getRandom() {                ListNode c = head;        int r = c.val;        for(int i=1;c.next != null;i++){                        c = c.next;            if(random.nextInt(i + 1) == i) r = c.val;                                }                return r;    }} 

Python:

from random import randintclass Solution(object):    def __init__(self, head):        """        @param head The linked list‘s head. Note that the head is guanranteed to be not null, so it contains at least one node.        :type head: ListNode        """        self.__head = head    # Proof of Reservoir Sampling:    # https://discuss.leetcode.com/topic/53753/brief-explanation-for-reservoir-sampling    def getRandom(self):        """        Returns a random node‘s value.        :rtype: int        """        reservoir = -1        curr, n = self.__head, 0        while curr:            reservoir = curr.val if randint(1, n+1) == 1 else reservoir            curr, n = curr.next, n+1        return reservoir

C++: 1

class Solution {public:    /** @param head The linked list‘s head. Note that the head is guanranteed to be not null, so it contains at least one node. */    Solution(ListNode* head) {        len = 0;        ListNode *cur = head;        this->head = head;        while (cur) {            ++len;            cur = cur->next;        }    }        /** Returns a random node‘s value. */    int getRandom() {        int t = rand() % len;        ListNode *cur = head;        while (t) {            --t;            cur = cur->next;        }        return cur->val;    }private:    int len;    ListNode *head;};

C++: 2

class Solution {public:    /** @param head The linked list‘s head. Note that the head is guanranteed to be not null, so it contains at least one node. */    Solution(ListNode* head) {        this->head = head;    }        /** Returns a random node‘s value. */    int getRandom() {        int res = head->val, i = 2;        ListNode *cur = head->next;        while (cur) {            int j = rand() % i;            if (j == 0) res = cur->val;            ++i;            cur = cur->next;        }        return res;    }private:    ListNode *head;};

  

類似題目:

398. Random Pick Index

 

 

[LeetCode] 382. Linked List Random Node 鏈表隨機節點

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.