Simple solution ever


  • 0
    J
    class Solution {
    private:    
        vector<int> nums;
    public:
        Solution(vector<int> nums) {
            this->nums = nums;
        }
        
        int pick(int target) {
            int result, count = 0;
            for(int i = 0 ; i < nums.size(); i++) {
                if(nums[i] != target) continue;
                count++;
                if(rand()%count == 0) result = i;
            }
            return result;
        }
    };
    
    

Log in to reply
 

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