382. Linked List Random Node

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 class Solution {
10     ArrayList<Integer> nums;
11     HashMap<Integer, Integer> locs;
12     java.util.Random rand = new java.util.Random();
13 
14     /**
15      * Initialize your data structure here.
16      */
17     public RandomizedSet() {
18         nums = new ArrayList<Integer>();
19         locs = new HashMap<Integer, Integer>();
20     }
21 
22     /**
23      * Inserts a value to the set. Returns true if the set did not already contain the specified element.
24      */
25     public boolean insert(int val) {
26         if (locs.containsKey(val)) return false;
27         locs.put(val, nums.size());
28         nums.add(val);
29         return true;
30     }
31 
32     /**
33      * Removes a value from the set. Returns true if the set contained the specified element.
34      */
35     public boolean remove(int val) {
36         if (!locs.containsKey(val)) return false;
37         int loc = locs.get(val);
38         if (loc < nums.size() - 1) { // not the last one than swap the last one with this val
39             int lastone = nums.get(nums.size() - 1);
40             nums.set(loc, lastone);
41             locs.put(lastone, loc);
42         }
43         locs.remove(val);
44         nums.remove(nums.size() - 1);
45         return true;
46     }
47 
48     /**
49      * Get a random element from the set.
50      */
51     public int getRandom() {
52         return nums.get(rand.nextInt(nums.size()));
53     }
54 }
55 
56 /**
57  * Your Solution object will be instantiated and called as such:
58  * Solution obj = new Solution(head);
59  * int param_1 = obj.getRandom();
60  */

 

posted @ 2017-10-25 20:05  daniel456  阅读(160)  评论(0编辑  收藏  举报