1. 程式人生 > >382 Linked List Random Node 鏈表隨機節點

382 Linked List Random Node 鏈表隨機節點

cnblogs 常數 空間復雜度 ble tee 返回 bject code IT

給定一個單鏈表,隨機選擇鏈表的一個節點,並返回相應的節點值。保證每個節點被選的概率一樣。
進階:
如果鏈表十分大且長度未知,如何解決這個問題?你能否使用常數級空間復雜度實現?
示例:
// 初始化一個單鏈表 [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()方法應隨機返回1,2,3中的一個,保證每個元素被返回的概率相等。
solution.getRandom();
詳見:https://leetcode.com/problems/linked-list-random-node/description/

C++:

方法一:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /** @param head The linked list‘s head.
        Note that the head is guaranteed to be not null, so it contains at least one node. */
    Solution(ListNode* head) {
        len=0;
        this->head=head;
        ListNode *cur=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;
};

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

方法二:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /** @param head The linked list‘s head.
        Note that the head is guaranteed 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;
        int 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;
};

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

參考:https://www.cnblogs.com/grandyang/p/5759926.html

382 Linked List Random Node 鏈表隨機節點