1. 题目描述
给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。
注意:
数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。
示例:
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) 应该返回索引 2,3 或者 4。每个索引的返回概率应该相等。
solution.pick(3);
// pick(1) 应该返回 0。因为只有nums[0]等于1。
solution.pick(1);
2. 题目代码
class Solution {
private int[] nums;
public Solution(int[] nums){
//将nums赋值给类变量
this.nums = nums;
}
public int pick(int target){
//定义变量求target的数量
int num = 0;
//定义index记录索引
int index = -1;
//遍历数组求num
for (int i = 0; i < nums.length; i++) {
if(target == nums[i]){
num++;
index = i;
}
}
//根据num来确定是否需要random
if(num == 1) return index;
index = 0;
int[] res = new int[num];
if(num > 1){
for (int i = 0; i < nums.length; i++) {
if(target == nums[i]){
res[index++] = i;
}
}
}
Random random = new Random();
int i = random.nextInt(num);
return res[i];
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/
3. 知识点
1. random.nextInt()
random.nextIn()的作用是随机生成一个int类型,因为int 的取值范围是 -2147483648——2147483647 ,所以生成的数也是处于这个范围
Random random = new Random();
System.out.println(random.nextInt());
结果:
-179138646
2. random.nextInt(int bound)
random.nextInt(int bound)方法的作用是生成一个0-参数bound范围内的随机数,左闭右开,但是要记住,参数bound必须是正数,不可为负数
Random random = new Random();
//输出[0,10)
System.out.println(random.nextInt(10));
结果:
9
3. random.nextDouble()
random.nextDouble()会生成一个0-1的double类型,而不是生成double取值范围中的数.左闭右开
4. random.nextFloat()
random.nextFloat()会生成一个随机的0-1之间的浮点型,大体同double一样
4. 参考
https://leetcode-cn.com/problems/random-pick-index/
https://blog.csdn.net/qq_39754721/article/details/94736251