leetcode 398. Random Pick Index

来源:互联网 发布:网络荐股诈骗 编辑:程序博客网 时间:2024/05/17 23:15

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);
这道题使用map和arraylist的那种方法已经老生常谈,我已经不屑于写了,要写就写space O(1) 的方法。
package leetcode;import java.util.Random;public class Random_Pick_Index_398 {int[] nums;Random random;public Random_Pick_Index_398(int[] nums){this.nums=nums;random=new Random();}        public int pick(int target) {    int count=0;    int resultIndex=-1;        for(int i=0;i<nums.length;i++){        if(nums[i]==target){        count++;        int r=random.nextInt(count);            if(r==count-1){            resultIndex=i;            }        }              }        return resultIndex;    }    public static void main(String[] args) {// TODO Auto-generated method stubint[] nums=new int[]{1,2,3,3,3};Random_Pick_Index_398 r=new Random_Pick_Index_398(nums);System.out.println(r.pick(3));}}

random.nextInt(count)指在[0,count)之间随机地选取一个整数。代码中不一定要 r==count-1,其实可以写成 r==0,因为只要保证当前概率是 1/count 即可。

举例,如果target有三个索引:1,2,3。
 一开始,1被选中的概率是1。
然后到2。 此时2被选中的概率是1/2。      2不被选中,仍然是1被选中的概率是1/2。
然后到3。 此时3被选中的概率是1/3。      3不被选中,保持之前选中的2的概率是2/3 * 1/2 = 1/3 。             
                                                                  3不被选中,保持之前选中的1的概率是2/3 * 1/2 = 1/3 。


原创粉丝点击