3939 */
4040public class RandomizedSet {
4141
42- private final Random random = new Random ();
43- private final Map <Integer , Integer > map = new HashMap <>();
44- private final List <Integer > keys = new ArrayList <>();
42+ private final Random random ;
43+ private final Map <Integer , Integer > map ;
44+ private final List <Integer > values ;
45+
46+ public RandomizedSet () {
47+ this .random = new Random ();
48+ this .map = new HashMap <>();
49+ this .values = new ArrayList <>();
50+ }
4551
4652 /**
4753 * Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
4854 */
4955 public boolean insert (int val ) {
5056 var isNotExist = !map .containsKey (val );
5157 if (isNotExist ) {
52- keys .add (val );
53- map .put (val , keys .size () - 1 );
58+ values .add (val );
59+ map .put (val , values .size () - 1 );
5460 }
5561 return isNotExist ;
5662 }
@@ -62,9 +68,9 @@ public boolean remove(int val) {
6268 var isExist = map .containsKey (val );
6369 if (isExist ) {
6470 var index = map .get (val );
65- keys .set (index , keys .getLast ());
66- map .put (keys .get (index ), index );
67- keys .removeLast ();
71+ values .set (index , values .getLast ());
72+ map .put (values .get (index ), index );
73+ values .removeLast ();
6874 map .remove (val );
6975 }
7076 return isExist ;
@@ -75,7 +81,7 @@ public boolean remove(int val) {
7581 * when this method is called). Each element must have the same probability of being returned.
7682 */
7783 public int getRandom () {
78- var index = random .nextInt (keys .size ());
79- return keys .get (index );
84+ var index = random .nextInt (values .size ());
85+ return values .get (index );
8086 }
8187}
0 commit comments