-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataStructures.java
72 lines (65 loc) · 1.83 KB
/
DataStructures.java
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package Stack;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
public class DataStructures {
List<Integer> nums;
Map<Integer, Set<Integer> > mp;
public Stream()
{
nums = new ArrayList<>();
mp = new HashMap<>();
}
public boolean insert(int val)
{
nums.add(val);
int index = nums.size() - 1;
if (!mp.containsKey(val)) {
mp.put(val, new HashSet<>());
}
mp.get(val).add(index);
return mp.get(val).size() == 1;
}
public boolean remove(int val)
{
if (!mp.containsKey(val)) {
return false;
}
Set<Integer> valIndices = mp.get(val);
int index = valIndices.iterator().next();
int lastIndex = nums.size() - 1;
valIndices.remove(index);
if (index != lastIndex) {
int lastNum = nums.get(lastIndex);
mp.get(lastNum).remove(lastIndex);
mp.get(lastNum).add(index);
Collections.swap(nums, index, lastIndex);
}
nums.remove(lastIndex);
if (valIndices.size() == 0) {
mp.remove(val);
}
return true;
}
public int getRandom()
{
int randomIndex
= (int)(Math.random() * nums.size());
return nums.get(randomIndex);
}
}
public static void main(String[] args) {
Stream myStream = new Stream();
System.out.println(myStream.insert(5));
System.out.println(myStream.insert(6));
System.out.println(myStream.insert(5));
System.out.println(myStream.remove(6));
System.out.println(myStream.remove(6));
System.out.println(myStream.getRandom());
}
}