Leetcode: Random Pick Index

Posted neverlandly

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode: 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);

Reservior Sampling

 1 public class Solution {
 2     int[] arr;
 3     Random random;
 4     
 5 
 6     public Solution(int[] nums) {
 7         arr = nums;
 8         random = new Random();
 9     }
10     
11     public int pick(int target) {
12         int count = 0;
13         int index = 0;
14         for (int i=0; i<arr.length; i++) {
15             if (arr[i] == target) {
16                 count++;
17                 if (random.nextInt(count) == 0) {
18                     index = i;
19                 }
20             }
21         }
22         return index;
23     }
24 }
25 
26 /**
27  * Your Solution object will be instantiated and called as such:
28  * Solution obj = new Solution(nums);
29  * int param_1 = obj.pick(target);
30  */

 

以上是关于Leetcode: Random Pick Index的主要内容,如果未能解决你的问题,请参考以下文章

leetcode_398 Random Pick Index(Reservoir Sampling)

leetcode 528. Random Pick with Weight

[LeetCode] Random Pick with Weight 根据权重随机取点

[leetcode]528. Random Pick with Weight按权重挑选索引

[LeetCode] Random Pick with Blacklist 带黑名单的随机选取

LeetCode 528. Random Pick with Weight / 497. Random Point in Non-overlapping Rectangles