본문 바로가기
LeetCode/2020 LeetCoding Challenge

LeetCode. Insert Delete GetRandom O(1)

by 벤진[Benzene] 2020. 6. 13.

Problem:

Design a data structure that supports all following operations in average O(1) time.

  1. insert(val): Inserts an item val to the set if not already present.
  2. remove(val): Removes an item val from the set if present.
  3. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

Example:

-Summary-

Using a dictionary data structure and method to implement.

dict.get(value) -> find the key in the dictionary

dict.pop(value) --> remove the key in the dictionary

 

이번 문제를 풀면서 random.choice라는 새로운 함수도 배우게 되었다.

https://www.w3schools.com/python/ref_random_choice.asp

 

Python Random choice() Method

Python Random choice() Method ❮ Random Methods Example Return a random element from a list: import random mylist = ["apple", "banana", "cherry"] print(random.choice(mylist)) Try it Yourself » Definition and Usage The choice() method returns a randomly s

www.w3schools.com

아래는 discussion에서 다른 방법 + 설명.

leetcode.com/problems/insert-delete-getrandom-o1/discuss/455253/Python-or-Super-Efficient-or-Detailed-Explanation

 

Python | Super Efficient | Detailed Explanation - LeetCode Discuss

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

댓글