首页 > 其他 > 详细

Linked List Random Node

时间:2017-02-19 20:19:09      阅读:218      评论:0      收藏:0      [点我收藏+]

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  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     List<Integer> list = new ArrayList<>();
11     
12     /** @param head The linked list‘s head.
13         Note that the head is guaranteed to be not null, so it contains at least one node. */
14     public Solution(ListNode head) {
15         while (head != null) {
16             list.add(head.val);
17             head = head.next;
18         }
19     }
20     
21     /** Returns a random node‘s value. */
22     public int getRandom() {
23         Random rand = new Random();
24         int n = rand.nextInt(list.size());
25         return list.get(n);
26     }
27 }
28 
29 /**
30  * Your Solution object will be instantiated and called as such:
31  * Solution obj = new Solution(head);
32  * int param_1 = obj.getRandom();
33  */

 

Linked List Random Node

原文:http://www.cnblogs.com/amazingzoe/p/6416727.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!