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 }

 

posted @ 2018-10-28 05:36  jasoncool1  阅读(85)  评论(0编辑  收藏  举报