Skip to content

398. Random Pick Index 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  Solution(vector<int>& nums) : nums(move(nums)) {}

  int pick(int target) {
    int ans = -1;
    int range = 0;

    for (int i = 0; i < nums.size(); ++i)
      if (nums[i] == target && rand() % ++range == 0)
        ans = i;

    return ans;
  }

 private:
  vector<int> nums;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public Solution(int[] nums) {
    this.nums = nums;
  }

  public int pick(int target) {
    int ans = -1;
    int range = 0;

    for (int i = 0; i < nums.length; ++i)
      if (nums[i] == target && rand.nextInt(++range) == 0)
        ans = i;

    return ans;
  }

  private int[] nums;
  private Random rand = new Random();
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def __init__(self, nums: List[int]):
    self.nums = nums

  def pick(self, target: int) -> int:
    ans = -1
    rng = 0
    for i, num in enumerate(self.nums):
      if num == target:
        rng += 1
        if random.randint(0, rng - 1) == 0:
          ans = i
    return ans