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();
class Solution { /** @param head The linked list"s head. Note that the head is guaranteed to be not null, so it contains at least one node. */ ListNode head; Random random; public Solution(ListNode head) { this.head = head; random = new Random(); } /** Returns a random node"s value. */ public int getRandom() { ListNode cur = head; int res = cur.val, count = 1; while (cur.next != null) { cur = cur.next; if (random.nextInt(count+1) == count) { res = cur.val; } count++; } return res; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/72335.html
摘要:題目要求要求從單鏈表中,隨機返回一個節點的值,要求每個節點被選中的概率是相等的。假如一共有個物品,需要從其中挑選出個物品,要求確保個物品中每個物品都能夠被等概率選中。對于這種等概率問題,簡答的做法是通過隨機數獲取選中物品的下標。 題目要求 Given a singly linked list, return a random nodes value from the linked li...
LeetCode[138] Copy List with Random Pointer A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of t...
摘要:大體意思就是,先復制到,順便將所有的放在再復制所有的到,順便將所有的放在最后令,令,將和分離,返回的頭結點 Problem A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. ...
摘要:棧迭代復雜度時間空間如果不算新鏈表的空間則是思路由于隨機指針有可能產生環路,我們不能直接沿著隨機指針的方向一個一個復制。同時我們又不能沿著指針直接復制,因為我們不知道隨機指針所指向的新節點是哪個。 Copy List with Random Pointer A linked list is given such that each node contains an additiona...
摘要:給定一個鏈表,每個節點包含一個額外增加的隨機指針,該指針可以指向鏈表中的任何節點或空節點。要求返回這個鏈表的深拷貝。提示你必須返回給定頭的拷貝作為對克隆列表的引用。確定隨機節點的關系之后再拆分鏈表。其時間復雜度為,空間復雜度為。 給定一個鏈表,每個節點包含一個額外增加的隨機指針,該指針可以指向鏈表中的任何節點或空節點。 要求返回這個鏈表的深拷貝。 A linked list is g...
閱讀 2516·2021-09-26 10:18
閱讀 3395·2021-09-22 10:02
閱讀 3192·2019-08-30 15:44
閱讀 3329·2019-08-30 15:44
閱讀 1836·2019-08-29 15:25
閱讀 2580·2019-08-26 14:04
閱讀 2042·2019-08-26 12:15
閱讀 2442·2019-08-26 11:43