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