美文网首页
LeetCode专题-编写特定用途的数据结构

LeetCode专题-编写特定用途的数据结构

作者: 山中散人的博客 | 来源:发表于2019-06-01 15:37 被阅读0次

398. Random Pick Index

Medium

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

题目大意:给定一个数组,要求编写一个数据结构,能随机地从数组中返回一个元素,元素值指定。

解题思路:利用python内置的random.choice()方法。

from random import choice
class Solution:

    def __init__(self, nums: List[int]):
        self.nums = nums
        self.size = len(nums)        

    def pick(self, target: int) -> int:
        idx_lst = [] #store idx of target
        for i in range(self.size):
            if self.nums[i] == target:
                idx_lst.append(i)

        if len(idx_lst) == 0: #input assumption if incorrect
            raise ValueError

        return choice(idx_lst) #choose one of the index randomly
        
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)

测试一下,

Success
[Details]
Runtime: 80 ms, faster than 85.87% of Python3 online submissions for Random Pick Index.
Memory Usage: 15.4 MB, less than 66.01% of Python3 online submissions for Random Pick Index.

相关文章

  • LeetCode专题-编写特定用途的数据结构

    398. Random Pick Index Medium Given an array of integers ...

  • leetcode

    leetcode leetcode to practice leetcode ac code 数组专题 done ...

  • 后端资料汇总

    1.leetcode https://leetcode-cn.com/problemset/all/ 2.数据结构...

  • LeetCode 专题:查找表

    LeetCode 专题:查找表 LeetCode 第 349 题:计算两个数组的交集 LeetCode 第 350...

  • vdesjs扩展自己的组件

    编写左侧组件json数据结构 左侧拖拽组件中需要编写数据结构,前往commoents/sub/LeftPanel....

  • (Boolan)C++设计模式 <十一> ——组合模

    “数据结构”模式 常常有一些组建在内部具有特定的数据结构,如果让客户程序依赖这些特定的数据结构,将极大的破坏组件的...

  • 数据结构

    一、数据结构简介 数据结构是以某种特定的布局方式存储数据的容器,所存储的数据结构是指相互之间存在一种或多种特定关系...

  • 代码时间优化

    数据结构,循环 改进算法,选择合适的数据结构 字典(dictionary) 与 列表(list) 用途:多数据成员...

  • 数据结构—概述

    数据结构概述 数据结构概述:程序设计 = 数据结构 + 算法数据结构:数据元素之间存在所有特定关系的集合,数据结构...

  • 寻找中位数

    LeetCode 295. Find Median from Data Stream设计一个数据结构,该数据结构动...

网友评论

      本文标题:LeetCode专题-编写特定用途的数据结构

      本文链接:https://www.haomeiwen.com/subject/kjkatctx.html