LeetCode398. Random Pick Index

1, topic Link

https://leetcode.com/problems/random-pick-index/

2, problem-solving ideas

Not speak directly look at the code> _ <

3, Code

  • Java
private int[] nums;
public Solution(int[] nums) {
    this.nums=nums;
}
public int pick(int target) {
    List<Integer> resultList = new ArrayList();
    for(int i=0,size=nums.length;i<size;i++){
        if(nums[i]==target){
            resultList.add(i);
        }
    }
    return resultList.get((int)(Math.random()*resultList.size()));
}

4 presentation of the results

Reproduced in: https: //www.jianshu.com/p/3a902ff4888f

Guess you like

Origin blog.csdn.net/weixin_34336292/article/details/91171015