leetcode 398. Random Pick Index(python)

描述

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.

Example 1:

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

Note:

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

解析

根据题意,给出了一个列表 nums ,只要用字典 d 记录下每个元素及其对应的所有出现过的索引组成的列表,然后通过一个随机数从 d[target] 中提取一个索引即可。

解答

class Solution(object):
    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.d = {}
        for i, v in enumerate(nums):
            if v in self.d:
                self.d[v].append(i)
            else:
                self.d[v] = [i]

    def pick(self, target):
        """
        :type target: int
        :rtype: int
        """
        arr = self.d[target]
        return arr[random.randint(0, len(arr) - 1)]

运行结果

Runtime: 288 ms, faster than 44.99% of Python online submissions for Random Pick Index.
Memory Usage: 22.9 MB, less than 34.15% of Python online submissions for Random Pick Index.

解析

根据题意,找出 target 在 nums 中出现过的索引列表,然后随机选择一个返回即可。

解答

class Solution(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.nums = nums

    def pick(self, target):
        """
        :type target: int
        :rtype: int
        """
        idxs = [i for i,num in enumerate(self.nums) if num==target]
        return random.choice(idxs)

运行结果

Runtime: 236 ms, faster than 96.48% of Python online submissions for Random Pick Index.
Memory Usage: 17 MB, less than 91.60% of Python online submissions for Random Pick Index.

解析

根据题意,遍历 nums ,找出第一次出现 target 的位置索引即可,此种解法不知道为何会报错,可能是因为结果没有随机性吧。

解答

class Solution(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.nums = nums


    def pick(self, target):
        """
        :type target: int
        :rtype: int
        """
        for i,num in enumerate(self.nums):
            if num!=target:
                continue
            else:
                return i

运行结果

Wrong 

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王大丫丫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值