Leetcode 398. Random Pick Index
2016-10-05 12:31
281 查看
398. Random Pick Index
Total Accepted: 4292 Total Submissions: 12426 Difficulty: MediumGiven 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);
Hide Company Tags
Hide Tags
Reservoir Sampling
Hide Similar Problems
(M) Linked List Random Node
思路:
一看标签,蓄水池抽样。但是input数组是给定的,并不是像另外那个linkedlist题一样,无法知道所有元素。
而且要求是输出值等于目标值的index,而且等概率。那么首先就得知道这些index,然后等概率输出。
要知道index就得遍历一遍比较。
不知道为啥标签是蓄水池抽样。。
参考这里。
public class Solution { // 306ms
int []nums;
Random r = new Random();
public Solution(int[] nums) {
this.nums = nums;
}
public int pick(int target) {
ArrayList<Integer> idxs = new ArrayList<Integer>();
for(int i=0;i<nums.length;i++){
if(target==nums[i]){
idxs.add(i);
}
}
return idxs.get(r.nextInt(idxs.size()));
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/
看了这里之后知道怎么用蓄水池抽样模拟了。
有个计数器,遍历数组,每次i++,如果nums[1] == target,针对count数目 random.nextInt(count)一次,如果为0替换结果。
注意事项是nextInt类似substring,所以要初始化为1。然而比上面慢了太多。
public class Solution { // 417ms private int[] nums; private Random random; public Solution(int[] nums) { this.nums = nums; this.random = new Random(); } public int pick(int target) { int result = -1; int count = 1; for (int i = 0; i < nums.length; i++) { if (nums[i] == target) { if (random.nextInt(count) == 0) { result = i; } count++; } } return result; } } /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * int param_1 = obj.pick(target); */
相关文章推荐
- LeetCode Binary Tree Maximum Path Sum
- Leetcode: Reverse Integer
- LeetCode Valid Palindrome
- [leetcode] Populating Next Right Pointers in Each Node II
- LeetCode刷题笔录Word Search
- Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Find Minimum in Rotated Sorted Array
- LeetCode:Sqrt(x)
- [LeetCode] House Robber II
- LeetCode Majority Element II
- [LeetCode94]Binary Tree Inorder Traversal
- 061 Rotate List [Leetcode]
- LeetCode Valid Sudoku
- leetcode笔记--ZigZag Conversion
- leetcode--- Symmetric Tree---平衡二叉树
- LeetCode 107. Binary Tree Level Order Traversal II(二叉树分层遍历)
- [Leetcode]204. Count Primes
- LeetCode--No.1--Two Sum
- [leetcode]257. Binary Tree Paths
- Leetcode 59. Spiral Matrix II