398. Random Pick Index
Posted The Tech Road
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了398. Random Pick Index相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/random-pick-index/description/
Reservoir Sampling
class Solution { public: vector<int> m; Solution(vector<int> nums) { m = nums; } int pick(int target) { int res = -1; for (int i = 0, cnt = 0; i < m.size(); i++) { if (m[i] == target) { cnt++; if (rand() % cnt == 0) res = i; } } return res; } };
以上是关于398. Random Pick Index的主要内容,如果未能解决你的问题,请参考以下文章