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()));
}