-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_remove_getRecent_min_max.java
More file actions
58 lines (57 loc) · 1.56 KB
/
Copy pathadd_remove_getRecent_min_max.java
File metadata and controls
58 lines (57 loc) · 1.56 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
50
51
52
53
54
55
56
57
58
class System{
TreeMap<Long,Integer> time_map = new TreeMap();
TreeMap<Integer,HashSet<Long>> value_map = new TreeMap();
int getMax() throws Exception{
if(value_map.size() == 0)
throw new Exception();
return value_map.lastKey();
}
int getMin() throws Exception{
if(value_map.size() == 0)
throw new Exception();
return value_map.firstKey();
}
int getRecent() throws Exception{
if(time_map.size() == 0)
throw new Exception();
return value_map.lastKey();
}
void add(long time, int price){
time_map.put(time,price);
if(!value_map.containsKey(price))
value_map.put(price,new HashSet<Long>());
value_map.get(price).add(time);
}
void update(long time, int price) throws Exception{
remove(time); // remove old value
add(time,price); // add new value
}
void remove(long time) throws Exception{
if(!time_map.containsKey(time))
throw new Exception();
int value = time_map.get(time);
time_map.remove(time);
value_map.get(value).remove(time);
if(value_map.get(value).size() == 0)// remove the set if empty
value_map.remove(value);
}
public static void main(String[] args) {
System s = new System();
try{
s.add(1,10);
s.add(2,100);
System.out.println(s.getMax());
System.out.println(s.getMin());
s.update(1,1000);
System.out.println(s.getMax());
System.out.println(s.getMin());
s.remove(1);
System.out.println(s.getMax());
System.out.println(s.getMin());
}
catch(Exception e){
}
finally{
}
}
}