给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。
注意:
数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。
public class RandomIndex {
int[] nums;
public RandomIndex(int[] nums) {
this.nums = nums;
}
public int pick(int target) {
int index = -1;
int count = 1;
Random ran = new Random();
for (int i = 0; i < nums.length; i++) {
if(nums[i] == target){
if (ran.nextInt(count++) == 0) {
index = i;
}
}
}
return index;
}
}