题目描述
思路
哈希表
不考虑数组大小,构造函数中使用哈希表记录nums中相同元素的下标。
对于pick操作,可以从哈希表中取出target对应的下标列表,然后随机选择其中一个下标并返回。
Python实现
class Solution:
def __init__(self, nums: List[int]):
self.idx = defaultdict(list)
for i, num in enumerate(nums):
self.idx[num].append(i)
def pick(self, target: int) -> int:
return choice(self.idx[target])
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)
Java实现
class Solution {
private Map<Integer, List<Integer>> map;
private Random random;
public Solution(int[] nums) {
random = new Random();
map = new HashMap<>();
int n = nums.length, i = 0;
for (;i < n; ++i) {
map.putIfAbsent(nums[i], new ArrayList<Integer>());
map.get(nums[i]).add(i);
}
}
public int pick(int target) {
List<Integer> lst = map.get(target);
return lst.get(random.nextInt(lst.size()));
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/