Leetcode 398 Solution
This article provides solution to leetcode question 398 (random-pick-index)
Access this page by simply typing in "lcs 398" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/random-pick-index
Solution
class Solution {
vector<int> m_nums;
public:
Solution(vector<int> nums) {
m_nums = nums;
}
int pick(int target) {
int cnt = 0;
int res = -1;
for (int i = 0; i < m_nums.size(); i++)
{
if (m_nums[i] != target)
continue;
cnt++;
if (rand() % cnt == 0)
res = i;
}
return res;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/