码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_398 Random Pick Index(Reservoir Sampling)

时间:2017-04-24 19:01:58      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:call   not   space   ber   生成   tar   extra   leetcode   tput   

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)

标签:call   not   space   ber   生成   tar   extra   leetcode   tput   

原文地址:http://www.cnblogs.com/ytq1016/p/6758131.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!