710 Random Pick with Blacklist】的更多相关文章

Question 710. Random Pick with Blacklist Solution 题目大意:给一个N,表示一个范围[0,N),给一个黑名单列表blacklist,其中blacklist中的元素在[0,N)范围内,调用pick方法的时候随机返回一个数,这个数满足 在[0,N)范围 不在blacklist内 要随机 思路:构造一个集合M,该M是 [0,N) - blacklist 的一个集合,调用pick时,返回[0,M)的一个随机数并根据这个随机数从集合M中取数即可. Java实…
1. 问题 给定一个黑名单,包含[0, N)的一些数,从[0, N)之间的非黑名单数中随机采样一个值. 2. 思路 字典映射 (1)计算黑名单数的长度,记作B,因为已经排除掉了B个元素,所以最后是从N-B个数中采样. (2)可以维护一个字典,表示从[0, N-B)到[0, N)之间的映射. (3)这样就可以每次采样从[0, N-B)之间取,采样后将值映射回[0, N). (4)然而这么做爆内存了(MemoryError),因为N的最大长度为10亿,B的最大长度为10万,N-B特别大. 时间复杂度…
Given a blacklist B containing unique integers from [0, N), write a function to return a uniform random integer from [0, N) which is NOT in B. Optimize it such that it minimizes the call to system’s Math.random(). Note: 1 <= N <= 1000000000 0 <=…
Given a blacklist B containing unique integers from [0, N), write a function to return a uniform random integer from [0, N) which is NOT in B. Optimize it such that it minimizes the call to system’s Math.random(). Note: 1 <= N <= 1000000000 0 <=…
Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight. Note: 1 <= w.length <= 10000 1 <= w[i] <= 10^5 pickIndex will be called at…
原题链接在这里:https://leetcode.com/problems/random-pick-with-weight/ 题目: Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight. Note: 1 <= w.l…
Question 398. Random Pick Index Solution 思路:重点是如果数据中有多个数target相等,要从这些数中随机取一个,根据例题 假设输入是: int[] nums = new int[]{1, 2, 3, 3, 3}; int target = 3; 模拟: 1 != target pass 2 != target pass 3 == target pick的概率 nextInt(1)==0的概率 1,返回这个index的概念是1 - 1/3 -1/3 = 1…
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 sp…
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 spa…
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 sp…