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
原文链接: https://www.cnblogs.com/dysjtu1995/p/12665806.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/340927
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!