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~i个结点时,直接放进结果集
- 遍历到第k(k > i)个结点时,以i/k的概率决定是否将结点i放进结果集。如果不放,直接忽略。如果放,就从结果集的i个结点中随机取出一个,替换为结点k
- 重复3,一直到尾节点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
ListNode head = null;
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
public Solution(ListNode head) {
this.head = head;
}
/** Returns a random node's value. */
public int getRandom() {
ListNode result = this.head;
ListNode curNode = this.head;
Random random = new Random();
for (int i = 1; curNode != null; i++) {
if (random.nextInt(i) == i - 1) {
result = curNode;
}
curNode = curNode.next;
}
return result.val;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/
Random Pick Index
Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.
Example:
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);
// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);
思路
Use random to ensure equal possibility, key point is save extra space.
- Create arraylist to store all index of target, and count total.
- Then use random from [0,total), to equally pick any element in the array.
Complexity: O(N)time O(m)space - # of target in nuts
class Solution {
private int[] nums;
public Solution(int[] nums) {
this.nums = nums;
}
public int pick(int target) {
List<Integer> list = new ArrayList<Integer>();
int count = 0;
int result = -1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
count++;
list.add(i);
}
}
Random random = new Random();
result = list.get(random.nextInt(count));
return result;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/