您的位置:首页 > 其它

Leetcode 398. Random Pick Index

2016-10-05 12:31 281 查看


398. Random Pick Index

Total Accepted: 4292 Total Submissions: 12426 Difficulty: Medium

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


Hide Company Tags
 Facebook

Hide Tags
 Reservoir Sampling

Hide Similar Problems
 (M) Linked List Random Node

思路:

一看标签,蓄水池抽样。但是input数组是给定的,并不是像另外那个linkedlist题一样,无法知道所有元素。

而且要求是输出值等于目标值的index,而且等概率。那么首先就得知道这些index,然后等概率输出。

要知道index就得遍历一遍比较。

不知道为啥标签是蓄水池抽样。。

参考这里

public class Solution { // 306ms
int []nums;
Random r = new Random();

public Solution(int[] nums) {
this.nums = nums;
}

public int pick(int target) {
ArrayList<Integer> idxs = new ArrayList<Integer>();
for(int i=0;i<nums.length;i++){
if(target==nums[i]){
idxs.add(i);
}
}
return idxs.get(r.nextInt(idxs.size()));
}

}

/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/
看了这里之后知道怎么用蓄水池抽样模拟了。

有个计数器,遍历数组,每次i++,如果nums[1] == target,针对count数目 random.nextInt(count)一次,如果为0替换结果。

注意事项是nextInt类似substring,所以要初始化为1。然而比上面慢了太多。

public class Solution { // 417ms
private int[] nums;
private Random random;

public Solution(int[] nums) {
this.nums = nums;
this.random = new Random();
}

public int pick(int target) {
int result = -1;
int count = 1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
if (random.nextInt(count) == 0) {
result = i;
}
count++;
}
}
return result;
}
}

/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Reservoir Sampling