Random Pick Index

53 阅读1分钟

Given an integer array nums 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.

Implement the Solution class:

Solution(int[] nums) Initializes the object with the array nums.
int pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i’s, then each index should have an equal probability of returning.

为了实现 Solution 类,我们需要在初始化时记录数组 nums,并在 pick 方法中随机选择一个目标值的索引。具体步骤如下:

  1. 初始化:在构造函数中保存数组 nums
  2. 随机选择:在 pick 方法中,找到所有目标值的索引,并从中随机选择一个。

以下是具体的实现代码:

import java.util.ArrayList; import java.util.List; import java.util.Random; class Solution { private int[] nums; private Random random; public Solution(int[] nums) { this.nums = nums; this.random = new Random(); } public int pick(int target) { List<Integer> indices = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { if (nums[i] == target) { indices.add(i); } } return indices.get(random.nextInt(indices.size())); } } // 示例用法 public class Main { public static void main(String[] args) { int[] nums = {1, 2, 3, 3, 3}; Solution solution = new Solution(nums); System.out.println(solution.pick(3)); // 可能输出 2, 3, 或 4 } }

解释

  1. 构造函数 Solution(int[] nums)

    • 将传入的数组 nums 保存到类的成员变量中。
    • 初始化一个 Random 对象,用于生成随机数。
  2. 方法 int pick(int target)

    • 创建一个 List<Integer> 来存储所有目标值的索引。
    • 遍历数组 nums,将所有等于 target 的索引添加到 indices 列表中。
    • 使用 random.nextInt(indices.size()) 生成一个随机索引,从 indices 列表中选择一个索引并返回。

这样,每次调用 pick 方法时,都会从所有目标值的索引中随机选择一个,确保每个索引有相同的概率被选中。