bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 398. Random Pick Index

398. Random Pick Index

Leetcode Solutions

Reservoir Sampling

  1. Initialize a variable count to 0 to keep track of the number of times the target has been seen.
  2. Iterate through the array nums.
  3. For each index i, check if nums[i] is equal to the target.
  4. If it is, increment count.
  5. Generate a random number between 1 and count (inclusive).
  6. If the random number is 1, select the current index i as the potential result.
  7. Continue iterating through the array.
  8. After the loop, return the last selected index.
UML Thumbnail

Caching Results Using a Hashmap

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...
bugfree Icon
OR