标签:
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 11 /** @param head The linked list‘s head. 12 Note that the head is guaranteed to be not null, so it contains at least one node. */ 13 14 private List<Integer> list=new ArrayList<>(); 15 16 public Solution(ListNode head) { 17 ListNode p=head; 18 int i=0; 19 while(p!=null) 20 { 21 list.add(p.val); 22 p=p.next; 23 i++; 24 } 25 } 26 27 /** Returns a random node‘s value. */ 28 public int getRandom() { 29 Random random=new Random(); 30 31 int q=random.nextInt(list.size()); 32 return list.get(q); 33 34 } 35 } 36 37 /** 38 * Your Solution object will be instantiated and called as such: 39 * Solution obj = new Solution(head); 40 * int param_1 = obj.getRandom(); 41 */
方法二:(参考别人的)
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 11 /** @param head The linked list‘s head. 12 Note that the head is guaranteed to be not null, so it contains at least one node. */ 13 14 private ListNode list=null; 15 private int size=0; 16 public Solution(ListNode head) { 17 list=head; 18 ListNode p=head; 19 while(p!=null) 20 { 21 p=p.next; 22 size++; 23 } 24 25 } 26 27 /** Returns a random node‘s value. */ 28 public int getRandom() { 29 ListNode ss=list; 30 int rand=(int)(Math.random()*size); 31 while(rand>0&&ss!=null) 32 { 33 ss=ss.next; 34 rand--; 35 } 36 return ss!=null?ss.val:0; 37 } 38 } 39 40 /** 41 * Your Solution object will be instantiated and called as such: 42 * Solution obj = new Solution(head); 43 * int param_1 = obj.getRandom(); 44 */
标签:
原文地址:http://www.cnblogs.com/ghuosaao/p/5778697.html