-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathFindingMKAverage.java
64 lines (57 loc) · 1.76 KB
/
FindingMKAverage.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
/*https://leetcode.com/problems/finding-mk-average/*/
class MKAverage {
int sum, total, m, k;
TreeMap<Integer,Integer> map = new TreeMap<Integer,Integer>();
Queue<Integer> queue = new LinkedList<Integer>();
public MKAverage(int m, int k) {
this.m = m;
this.k = k;
this.sum = this.total = 0;
this.map = new TreeMap<Integer,Integer>();
this.queue = new LinkedList<Integer>();
}
public void addElement(int num) {
++total;
sum += num;
queue.add(num);
map.put(num,map.getOrDefault(num,0)+1);
if (total > m)
{
--total;
int first = queue.poll();
sum -= first;
map.put(first,map.get(first)-1);
if (map.get(first) == 0) map.remove(first);
}
}
public int calculateMKAverage() {
if (total < m) return -1;
int count = k, sumCopy = sum;
for (Map.Entry entry : map.entrySet())
{
if (count == 0) break;
int key = (Integer)entry.getKey();
int value = (Integer)entry.getValue();
int min = Math.min(count,value);
count -= min;
sumCopy -= min*key;
}
count = k;
for (Map.Entry entry : map.descendingMap().entrySet())
{
if (count == 0) break;
int key = (Integer)entry.getKey();
int value = (Integer)entry.getValue();
int min = Math.min(count,value);
count -= min;
sumCopy -= min*key;
}
return (sumCopy/(m-2*k));
}
}
/**
* Your MKAverage object will be instantiated and called as such:
* MKAverage obj = new MKAverage(m, k);
* obj.addElement(num);
* int param_2 = obj.calculateMKAverage();
*/