给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。
注意:
数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。
import java.util.Random;
class Solution {
Random random = new Random();
int[] nums;
public Solution(int[] _nums) {
nums = _nums;
}
public int pick(int target) {
int n = nums.length, ans = 0;
for (int i = 0, cnt = 0; i < n; i++) {
if (nums[i] == target) {
cnt++;
if (random.nextInt(cnt) == 0) ans = i;
}
}
return ans;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/