LeetCode_随机数索引【中等】
正题:
题目:
示例:
nt[] nums = new int[] {1,2,3,3,3};
olution solution = new Solution(nums);
// pick(3) 应该返回索引 2,3 或者 4。每个索引的返回概率应该相等。
solution.pick(3);
// pick(1) 应该返回 0。因为只有nums[0]等于1。
solution.pick(1);
解题思路:
方法:哈希表
思路与算法:
代码如下(示例):
class Solution {
Map<Integer, List<Integer>> pos;
Random random;
public Solution(int[] nums) {
pos = new HashMap<>();
random = new Random();
for (int i = 0;i < nums.length;i++){
//putIfAbsent方法:用于给map集合添加数据,但是该方法与put方法有所不同
//当key不存在时,该方法会保存数据;当key存在时,则不会对其保存
pos.putIfAbsent(nums[i], new ArrayList<>());
pos.get(nums[i]).add(i);
}
}
public int pick(int target) {
List<Integer> indices = pos.get(target);
return indices.get(random.nextInt(indices.size()));
}
}
执行用时:
- 执行用时: 69 ms;
- 内存消耗: 50.4 MB。