-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathInsertDeleteGetrandomO1.java
More file actions
31 lines (26 loc) · 941 Bytes
/
InsertDeleteGetrandomO1.java
File metadata and controls
31 lines (26 loc) · 941 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.dbc;
import java.util.*;
public class InsertDeleteGetrandomO1 {
private final List<Integer> nums = new ArrayList<>();
private final Map<Integer, Integer> index = new HashMap<>();
Random random = new Random();
public InsertDeleteGetrandomO1() {
}
public boolean insert(int val) {
if (this.index.containsKey(val)) return false;
this.index.put(val, this.nums.size());
this.nums.add(val);
return true;
}
public boolean remove(int val) {
if (!this.index.containsKey(val)) return false;
this.nums.set(this.index.get(val), this.nums.get(this.nums.size() - 1));
this.index.put(this.nums.get(this.nums.size() - 1), this.index.get(val));
this.nums.remove(this.nums.size() - 1);
this.index.remove(val);
return true;
}
public int getRandom() {
return this.nums.get(random.nextInt(this.nums.size()));
}
}