leetcode_398 Random Pick Index(Reservoir Sampling)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode_398 Random Pick Index(Reservoir Sampling)相关的知识,希望对你有一定的参考价值。
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);
public class Solution { int[] nums; Random r=new Random(); public Solution(int[] nums) { this.nums=nums; } public int pick(int target) { ArrayList al=new ArrayList(); int count=0; for(int i=0;i<nums.length;i++){ if(target==nums[i]){ count++; al.add(i); } } int ans=r.nextInt(count); return (int)al.get(ans); } } /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * int param_1 = obj.pick(target); */
随机方法:水塘抽样
遍历整个数组,如果数组的值不等于target,直接跳过;如果等于target,计数器count加1,然后我们在[0,count]范围内随机生成一个数字
把数组等于target的索引存在Arraylist对象中,随机生成,取到最终结果
以上是关于leetcode_398 Random Pick Index(Reservoir Sampling)的主要内容,如果未能解决你的问题,请参考以下文章