Random Pick Index

https://leetcode.com/problems/random-pick-index/

class Solution {
public:

    vector<int> num;

    Solution(vector<int> nums) {
        srand(time(NULL));
        num = nums;
    }

    int pick(int target) {

        int res = -1;
        int count = 0;
        for(int i = 0; i<num.size(); i++)
        {
            if(num[i] != target)
            {
                continue;
            }

            if(rand()%(++count) == 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);
 */

results matching ""

    No results matching ""