public class Solution {
Map<Integer, String> map;
Random random;
public Solution(int[] nums) {
map = new HashMap<Integer, String>();
random = new Random();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) map.put(nums[i], map.get(nums[i]) + "," + String.valueOf(i));
else map.put(nums[i], String.valueOf(i));
}
}
public int pick(int target) {
String s = map.get(target);
String[] indices = s.split(",");
int r = random.nextInt(indices.length);
return Integer.valueOf(indices[r]);
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/
LeetCode 398. Random Pick Index
最新推荐文章于 2024-08-20 10:34:34 发布