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();
}