Skip to content

Commit 7042d68

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 380_Insert_Delete_GetRandom_O(1).java
1 parent bed86de commit 7042d68

File tree

1 file changed

+16
-17
lines changed

1 file changed

+16
-17
lines changed
Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
class RandomizedSet {
2-
HashMap<Integer, Integer> hm;
3-
ArrayList<Integer> keys;
4-
Random generator;
2+
private List<Integer> list;
3+
private Map<Integer, Integer> hm;
54

65
/** Initialize your data structure here. */
76
public RandomizedSet() {
8-
hm = new HashMap<Integer, Integer>();
9-
keys = new ArrayList<Integer>();
10-
generator = new Random();
7+
list = new ArrayList<>();
8+
hm = new HashMap<>();
119
}
1210

1311
/**
@@ -19,8 +17,8 @@ public boolean insert(int val) {
1917
return false;
2018
}
2119

22-
hm.put(val, keys.size());
23-
keys.add(val);
20+
list.add(val);
21+
hm.put(val, list.size() - 1);
2422
return true;
2523
}
2624

@@ -33,21 +31,22 @@ public boolean remove(int val) {
3331
return false;
3432
}
3533

36-
int removeIdx = hm.get(val);
34+
int idx = hm.get(val);
35+
int lastElement = list.get(list.size() - 1);
3736

38-
if (removeIdx < keys.size() - 1) {
39-
int lastVal = keys.get(keys.size() - 1);
40-
keys.set(removeIdx, lastVal);
41-
hm.put(lastVal, removeIdx);
42-
}
43-
44-
keys.remove(keys.size() - 1);
37+
list.set(idx, lastElement);
38+
list.remove(list.size() - 1);
39+
hm.put(lastElement, idx);
4540
hm.remove(val);
41+
4642
return true;
4743
}
4844

4945
/** Get a random element from the set. */
5046
public int getRandom() {
51-
return keys.get(generator.nextInt(hm.size()));
47+
Random rand = new Random();
48+
int randIdx = rand.nextInt(list.size());
49+
50+
return list.get(randIdx);
5251
}
5352
}

0 commit comments

Comments
 (0)