398. Random Pick Index

Posted gopanama

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了398. Random Pick Index相关的知识,希望对你有一定的参考价值。

 

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

 

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

398. Random Pick Index

398. Random Pick Index

[LC] 398. Random Pick Index

398. Random Pick Index

leetcode_398 Random Pick Index(Reservoir Sampling)

398 Random Pick Index 随机数索引