LeetCode 398. Random Pick Index

简介: 给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。

v2-b28ce54a837f68dcc089a7127afb6a20_1440w.jpg

Description



Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.


Note:

The array size can be very large. Solution that uses too much extra space will not pass the judge.


Example:


int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);
// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);


描述



给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。


注意:

数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。


示例:

int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) 应该返回索引 2,3 或者 4。每个索引的返回概率应该相等。
solution.pick(3);
// pick(1) 应该返回 0。因为只有nums[0]等于1。
solution.pick(1);


来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/random-pick-index

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


思路


  • 这道题和第 382 题 Linked List Random Node 解法类似。
  • 遍历给定的数组,统计当前满足条件的数的个数 n,用 random 函数随机生成一个 1 到 n 的数,如果选到了 n ,就把当前的数和最终结果替换。


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-08-30 19:55:46
# @Last Modified by:   何睿
# @Last Modified time: 2019-08-30 20:17:06
import heapq
import random
from typing import List
class Solution:
    def __init__(self, nums: List[int]):
        self.arrays = nums
    def pick(self, target: int) -> int:
        hep = []
        for i, v in enumerate(self.arrays):
            if v == target:
                # heap 维护最小堆,random.random() 会被用来比较
                # 没个数被弹出的概率都是一样的
                heapq.heappush(hep, (random.random(), i))
        _, index = heapq.heappop(hep)
        return index
    def pick2(self, target: int) -> int:
        n, res = 0, 0
        for x in filter(lambda x: x[1] == target, enumerate(self.arrays)):
            n += 1
            if random.randint(1, n) == n: # 解法思路同蓄水题解法思路
                res = x[0]
        return res

源代码文件在 这里


目录
相关文章
|
8月前
|
C++
Leetcode Copy List with Random Pointer(面试题推荐)
给大家推荐一道leetcode上的面试题,这道题的具体讲解在《剑指offer》的P149页有思路讲解,如果你手头有这本书,建议翻阅。
32 0
|
Go
leetcode-每日一题1408. 数组中的字符串匹配(暴力枚举)和Golang里关于Index方法和Contains方法区别
题目要求我们找到字符串数组中存在字符串是其他单词的子字符串,看到题目给我们的n的范围是[1,100],所以我们可以通过暴力枚举用两个for循环一层指子串一层指找存在这个子串的单词,找到则找下个一个子串
124 0
leetcode-每日一题1408. 数组中的字符串匹配(暴力枚举)和Golang里关于Index方法和Contains方法区别
LeetCode 382. Linked List Random Node
给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。
51 0
LeetCode 382. Linked List Random Node
|
人工智能 索引
Leetcode-Easy 852. Peak Index in a Mountain Array
Leetcode-Easy 852. Peak Index in a Mountain Array
85 0
|
索引
LeetCode 599: 两个列表的最小索引总和 Minimum Index Sum of Two Lists
题目: 假设 Andy 和 Doris 想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。 Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings. 你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。
859 0
LeetCode 138:复制带随机指针的链表 Copy List with Random Pointer
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。 要求返回这个链表的深拷贝。 A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
827 0
[LeetCode] Minimum Index Sum of Two Lists 两个表单的最小坐标和
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
1094 0