OA - Randomly Choose k Samples
Written on January 9, 2016
Tweet
Reservoir sampling is a family of randomized algorithms for randomly choosing k samples from a list of n items, where n is either a very large or unknown number.
public class Solution {
public static int[] randamPick(int[] arr, int k) {
int[] result = new int[k];
int i = 0;
for (; i < k; i++) {
result[i] = arr[i];
}
Random rand = new Random();
for (; i < arr.length; i++) {
int j = rand.nextInt(i + 1);
if (j < k) {
result[j] = arr[i];
}
}
return result;
}
}
class Solution(object):
def randam_picket(self, nums, k):
if not nums or not k:
return []
ret = nums[0:k]
for i, num in enumerate(nums):
j = random.randint(0, i)
if j < k:
ret[i] = num
return ret