398 Random Pick Index

class Solution {

    int[] nums;
    Random rand;

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

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

        for (int i = 0; i < this.nums.length; i++){
            if (this.nums[i] != target) continue;

            if (rand.nextInt(++count) == 0) result = i;
        }

        return result;
    }
}

/**
 * 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 ""