398. Random Pick Index

Link

Solution

找出所有可能,隨機回傳其中一個可能

class Solution {
    int[] nums;
    Random random;
    public Solution(int[] nums) {
        this.nums = nums;
        random = new Random();
    }
    
    public int pick(int target) {
        List<Integer> indexs = new ArrayList<>();
        for(int i = 0; i < nums.length; i++){
            if(nums[i] == target){
                indexs.add(i);
            }
        }
        int i = random.nextInt(indexs.size());
        return indexs.get(i);
    }
}

Last updated

Was this helpful?