398. Random Pick Index
作者:
夜皇雪 | 来源:发表于
2016-12-12 16:03 被阅读0次public class Solution {
int[] nums;
Random rnd;
public Solution(int[] nums) {
this.nums = nums;
this.rnd = new Random();
}
public int pick(int target) {
int result = -1;
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != target)
continue;
if (rnd.nextInt(++count) == 0)
result = i;
}
return result;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/
本文标题:398. Random Pick Index
本文链接:https://www.haomeiwen.com/subject/niimmttx.html
网友评论