1、题目链接
https://leetcode.com/problems/random-pick-index/
2、解题思路
不说话,直接看代码>_<
3、代码
- 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()));
}
网友评论