398. Random Pick Index

;  |     Back to Homepage   |     Back to Code List


class Solution {
    private Random random; // Math.random
    private int[] a;
    public Solution(int[] nums) {
        a = nums;
        random = new Random();
    }
    
    public int pick(int target) {
        int count = 0;
        int res = 0;
        
        for (int i = 0; i < a.length; i++) {
            if (a[i] == target) {
                count++;
                
                if (random.nextInt(count) == 0) {
                    res = i;
                }
            }
        }
        
        return res;
    }
}