Problem 398

Posted by Ruizhi Ma on October 29, 2020

Solution URL

https://leetcode.com/submissions/detail/414688374/

代码

class Solution {
    //ans: https://leetcode-cn.com/problems/random-pick-index/solution/398-sui-ji-shu-suo-yin-sui-ji-ming-zhong-fa-by-jas/
    private int[] nums;
    private Random r;

    public Solution(int[] nums) {
        this.nums = nums;
        r = new Random();
    }

    public int pick(int target) {
        int ans = -1;
        int count = 0;

        for(int i = 0; i < nums.length; i++){
            //如果没有命中,继续
            if(nums[i] != target) continue;

            count++;

            if(r.nextInt(count) == 0){
                ans = i;
            }
        }
        return ans;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int param_1 = obj.pick(target);
 */