LeetCode_随机数索引

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

来源:LeetCode-398.随机数索引


解题思路:

方法:哈希表

思路与算法:

对于构造函数,我们可以使用一个哈希表pos来记录数组nums中相同元素的下标。而对于pick操作,我们可以从pos中取出target对应的下标列表,然后随机选取一个即可。


代码如下(示例):
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。

业精于勤,荒于嬉;行成于思,毁于随。——韩愈

你可能感兴趣的:(LeetCode题解,leetcode,算法,java)