-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsert_Delete_GetRandom_O_of_1.java
More file actions
49 lines (43 loc) · 1.17 KB
/
Insert_Delete_GetRandom_O_of_1.java
File metadata and controls
49 lines (43 loc) · 1.17 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.io.*;
import java.lang.*;
import java.util.*;
public class Insert_Delete_GetRandom_O_of_1 {
class RandomizedSet {
HashMap<Integer , Integer> hm = new HashMap<>();
ArrayList<Integer> al = new ArrayList<>();
public RandomizedSet() {
}
public boolean insert(int val) {
if(hm.containsKey(val))
{
return false;
}
else
{
al.add(val);
hm.put(val , al.size()-1);
return true;
}
}
public boolean remove(int val) {
if(hm.containsKey(val))
{
//al.remove(hm.get(val));
al.set(hm.get(val) , al.get(al.size()-1));
hm.put(al.get(al.size()-1) , hm.get(val));
hm.remove(val);
al.remove(al.size()-1);
return true;
}
else
{
return false;
}
}
public int getRandom() {
double r = Math.random();
int rn = (int)(r * (al.size() - 0)) + 0;
return al.get(rn);
}
}
}