Problem:
Design a data structure that supports all following operations in average O(1) time.
- insert(val): Inserts an item val to the set if not already present.
- remove(val): Removes an item val from the set if present.
- 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에서 다른 방법 + 설명.
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]
'LeetCode > 2020 LeetCoding Challenge' 카테고리의 다른 글
LeetCode. Cheapest Flights Within K Stops (0) | 2020.06.15 |
---|---|
LeetCode. Largest Divisible Subset (0) | 2020.06.14 |
LeetCode. Sort Colors (0) | 2020.06.12 |
LeetCode. Search Insert Position [Binary Search] (0) | 2020.06.11 |
LeetCode. Is Subsequence (0) | 2020.06.10 |
댓글