398. Random Pick Index

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);

解法:Reservoir Sampling

public class ReservoirSamplingTest {

    private int[] pool; // 所有数据
    private final int N = 100000; // 数据规模
    private Random random = new Random();

    @Before
    public void setUp() throws Exception {
        // 初始化
        pool = new int[N];
        for (int i = 0; i < N; i++) {
            pool[i] = i;
        }
    }

    private int[] sampling(int K) {
        int[] result = new int[K];
        for (int i = 0; i < K; i++) { // 前 K 个元素直接放入数组中
            result[i] = pool[i];
        }

        for (int i = K; i < N; i++) { // K + 1 个元素开始进行概率采样
            int r = random.nextInt(i + 1);
            if (r < K) {
                result[r] = pool[i];
            }
        }

        return result;
    }

    @Test
    public void test() throws Exception {
        for (int i : sampling(100)) {
            System.out.println(i);
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,871评论 0 10
  • 这是一座海纳百川的城市,街头巷尾,有着各地各国各种美食。从西北菜,川菜,湘菜,东北菜,港式茶餐厅,各式火锅,潮州菜...
    若愚123阅读 503评论 6 9
  • 今天是丁酉九.九重阳节,先道一声重阳节快乐!天气这么好除了晒晒被子,坐在太阳下把自己也晒晒。突发奇想何不把原来写的...
    一羊55阅读 941评论 0 1
  • 【江南行走·早茶记】吃早茶是一种生活方式,属于广式的精致,属于缓慢悠长的节奏…… 最缓慢悠长的,是新疆过来的手机信...
    拈花老夏阅读 748评论 4 4
  • 2016年末,内政参议院与小朝歌发表关于年终总结的重要讲话:2016年作为少帅挥之不去的荒凉,也随着2017年2月...
    少帅刘俊秀阅读 198评论 0 0

友情链接更多精彩内容