Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e8b618d

Browse files
380.insert delete getrandom O(1)
1 parent 839236b commit e8b618d

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

‎380-insert-delete-getrandom.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import java.util.*;
2+
3+
class RandomizedSet {
4+
ArrayList<Integer> a;
5+
Random random;
6+
public RandomizedSet() {
7+
a = new ArrayList<>();
8+
random = new Random();
9+
}
10+
public boolean insert(int val) {
11+
if (a.contains(val)) {
12+
return false;
13+
}
14+
a.add(val);
15+
return true;
16+
}
17+
18+
19+
public boolean remove(int val) {
20+
int index = a.indexOf(val);
21+
if (index == -1) {
22+
return false;
23+
}
24+
int lastValue = a.get(a.size() - 1);
25+
a.set(index, lastValue);
26+
a.remove(a.size() - 1);
27+
return true;
28+
}
29+
30+
31+
public int getRandom() {
32+
int randomIndex = random.nextInt(a.size()); //
33+
return a.get(randomIndex);
34+
}
35+
36+
}
37+
38+
class Main {
39+
public static void main(String[] args) {
40+
RandomizedSet randomizedSet = new RandomizedSet();
41+
42+
System.out.println(randomizedSet.insert(1));
43+
System.out.println(randomizedSet.remove(2));
44+
System.out.println(randomizedSet.insert(2));
45+
System.out.println(randomizedSet.getRandom());
46+
System.out.println(randomizedSet.remove(1));
47+
System.out.println(randomizedSet.insert(2));
48+
System.out.println(randomizedSet.getRandom());
49+
50+
}
51+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /