My C++ solutions


  • 0
    1. Hash Table, MLE.
    class Solution {
    public:
        Solution(vector<int> nums) {
            for(int i = 0; i < nums.size(); i++) m[nums[i]].push_back(i);
        }
        
        int pick(int target) {
            //srand((unsigned)time(NULL));
            int index = rand() % m[target].size();
            return m[target][index];
        }
        
    private:
        unordered_map<int, vector<int>>m;
    };
    
    1. Reservoir Sampling
    class Solution {
    public:
        Solution(vector<int> nums) {
            this->nums = nums;
        }
        
        int pick(int target) {
            int res = -1, count = 0;
            for(int i = 0; i < nums.size(); i++){
                if(nums[i] != target) continue;
                if(res == -1) res = i, count++;
                else{
                    count++;
                    if(rand() % count == 0) res = i;
                }
            }
            return res;
        }
        
    private:
        vector<int>nums;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.