Skip to content

Commit d55705b

Browse files
committed
Add solution #380
1 parent 7c719aa commit d55705b

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,7 @@
249249
371|[Sum of Two Integers](./0371-sum-of-two-integers.js)|Medium|
250250
372|[Super Pow](./0372-super-pow.js)|Medium|
251251
374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium|
252+
380|[Insert Delete GetRandom O(1)](./0380-insert-delete-getrandom-o1.js)|Medium|
252253
383|[Ransom Note](./0383-ransom-note.js)|Easy|
253254
387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy|
254255
389|[Find the Difference](./0389-find-the-difference.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* 380. Insert Delete GetRandom O(1)
3+
* https://leetcode.com/problems/insert-delete-getrandom-o1/
4+
* Difficulty: Medium
5+
*
6+
* Implement the RandomizedSet class:
7+
* - RandomizedSet() Initializes the RandomizedSet object.
8+
* - bool insert(int val) Inserts an item val into the set if not present. Returns true if the
9+
* item was not present, false otherwise.
10+
* - bool remove(int val) Removes an item val from the set if present. Returns true if the item
11+
* was present, false otherwise.
12+
* - int getRandom() Returns a random element from the current set of elements (it's guaranteed
13+
* that at least one element exists when this method is called). Each element must have the
14+
* same probability of being returned.
15+
*
16+
* You must implement the functions of the class such that each function works in average O(1)
17+
* time complexity.
18+
*/
19+
20+
21+
var RandomizedSet = function() {
22+
this.set = new Set();
23+
};
24+
25+
/**
26+
* @param {number} val
27+
* @return {boolean}
28+
*/
29+
RandomizedSet.prototype.insert = function(val) {
30+
const hasValue = this.set.has(val);
31+
this.set.add(val);
32+
return !hasValue;
33+
};
34+
35+
/**
36+
* @param {number} val
37+
* @return {boolean}
38+
*/
39+
RandomizedSet.prototype.remove = function(val) {
40+
const hasValue = this.set.has(val);
41+
this.set.delete(val);
42+
return hasValue;
43+
};
44+
45+
/**
46+
* @return {number}
47+
*/
48+
RandomizedSet.prototype.getRandom = function() {
49+
const item = Array.from(this.set);
50+
const randomIndex = Math.floor(Math.random() * item.length);
51+
return item[randomIndex];
52+
};

0 commit comments

Comments
 (0)