Notice
Recent Posts
Recent Comments
Link
.Zzumbong
[leetCode/JS] 380. Insert Delete GetRandom O(1) ๋ณธ๋ฌธ
๋์ด๋ [ ๐ค ] Medium
๋ฌธ์ ์ค๋ช
Implement the RandomizedSet
class:
RandomizedSet()
Initializes theRandomizedSet
object.bool insert(int val)
Inserts an itemval
into the set if not present. Returnstrue
if the item was not present,false
otherwise.bool remove(int val)
Removes an itemval
from the set if present. Returnstrue
if the item was present,false
otherwise.int getRandom()
Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
You must implement the functions of the class such that each function works in average O(1)
time complexity.
RandomizedSet ํด๋์ค๋ฅผ ๋ง๋ค์ด์
insert(val) ๋ก value๋ฅผ ๋ฃ๊ณ , remove()๋ก ์ง์ฐ๊ณ , getRandom() ๋๋ค 1๊ฐ ๋ฝ์์จ๋ค.
์ ์ถ๋ ฅ ์
Example 1:
Input
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]
Explanation
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
Constraints
-231 <= val <= 231 - 1
- At most
2 * 105
calls will be made toinsert
,remove
, andgetRandom
. - There will be at least one element in the data structure when
getRandom
is called.
๋ด ์๋ฃจ์
- ์ Medium ์ด์ง.. ์ถ์ ๋ฌธ์ ๋ค.
- array๋ก ํด๋ณผ๊น ํ๋ค๊ฐ ๊ทธ๋ฅ Set์ด ์ง์ฐ๊ธฐ ์ฌ์์ ํด๋ดค๋ค.
- ๋์ ์ข ๋๋ฆฐ ๊ฒ ๊ฐ๋ค.
class RandomizedSet {
constructor() {
this.nums = new Set();
}
insert(val) {
if(this.nums.has(val)) {
return false;
}
this.nums.add(val);
return true;
}
remove(val) {
if(this.nums.has(val)) {
this.nums.delete(val)
return true;
}
return false;
}
getRandom() {
return [...this.nums][Math.floor(Math.random() * this.nums.size)]
}
}
๊ฐ์ํ
- ์ฌ์ ๋ค! ์ค๋๋ง์ ์ฝ๊ณ ์ฌ๋ฏธ์๋ ๊ฐ๋ฒผ์ด ๋ฌธ์
'coding test > leetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[leetCode/JS] 1704. Determine if String Halves Are Alike (0) | 2022.12.01 |
---|---|
[leetCode/JS] 1207. Unique Number of Occurrences (0) | 2022.11.30 |
[leetCode/JS] 2225. Find Players With Zero or One Losses (0) | 2022.11.28 |
[leetCode/JS] 446. Arithmetic Slices II - Subsequence (0) | 2022.11.27 |
[leetCocd/JS] 907. Sum of Subarray Minimums (0) | 2022.11.25 |
0 Comments