398. 随机数索引
题目来源:398. 随机数索引
2022.04.25 每日一题
LeetCode 题解持续更新中GitHub仓库地址 CSDN博客地址
今天的题目比较简单,逻辑和这道题目 380. O(1) 时间插入、删除和获取随机元素 差不多,我们使用 HashMap 将数组的元素以及其索引分别当作 key 以及 val 存入 HashMap 中,然后随机返回索引数组中的索引值即可。
class Solution {
// 创建一个 HashMap 用来统计 数组中的值以及 对应的索引
unordered_map<int, vector<int>> map;
public:
Solution(vector<int> &nums) {
int len = nums.size();
// 将数组中的元素 作为 key 值放入,val 放入对应的 索引值
for (int i = 0; i < len; i++) {
vector<int> temp = map[nums[i]];
temp.push_back(i);
map[nums[i]] = temp;
}
}
int pick(int target) {
// 获取对应的值 的 索引列表
vector<int> temp = map[target];
// 随机返回一个索引
return temp[rand() % temp.size()];
}
};
class Solution {
// 创建一个 HashMap 用来统计 数组中的值以及 对应的索引
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
// 随机
Random random = new Random();
public Solution(int[] nums) {
int len = nums.length;
// 将数组中的元素 作为 key 值放入,val 放入对应的 索引值
for (int i = 0; i < len; i++) {
ArrayList<Integer> list = map.getOrDefault(nums[i], new ArrayList<>());
list.add(i);
map.put(nums[i], list);
}
}
public int pick(int target) {
// 获取对应的值 的 索引列表
ArrayList<Integer> list = map.getOrDefault(target, new ArrayList<>());
// 随机返回一个索引
return list.get(random.nextInt(list.size()));
}
}