Description:
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,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();
思路:
取最後一個節點並替換爲結果的概率爲 1 / n
設取倒數第二個節點的概率爲 x, 則 x * (1 - 1 / n) = 1 / n, x = 1 / (n - 1), 表示取倒數第二個節點, 並且不取最後一個節點
那麼可以每次生成一個 [0, k]的隨機數, 如果隨機到 0就替換
這樣就可以保證每次取出的節點的概率爲 1 / n
時間複雜度O(n), 空間複雜度O(1)
代碼:
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): head(head) {
}
/** Returns a random node's value. */
int getRandom() {
ListNode* cur = head -> next;
int result = head -> val, i = 2;
while (cur)
{
if (!(rand() % i)) result = cur -> val;
i++;
cur = cur -> next;
}
return result;
}
private:
ListNode* head;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(head);
* int param_1 = obj->getRandom();
*/
Java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
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() {
ListNode cur = head.next;
int result = head.val, i = 2;
Random random = new Random();
while (cur != null) {
if (random.nextInt(i) == 0) result = cur.val;
i++;
cur = cur.next;
}
return result;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/
Python:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def __init__(self, head: ListNode):
"""
@param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node.
"""
self.head = head
def getRandom(self) -> int:
"""
Returns a random node's value.
"""
result, i, cur = self.head.val, 2, self.head.next
while cur:
if not random.randrange(i):
result = cur.val
i += 1
cur = cur.next
return result
# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()