求出 MK 平均值
难度:
标签:
题目描述
代码结果
运行时间: 541 ms, 内存: 50.6 MB
/*
* MKAverage class implementation in Java using Java Stream API
*
* Thought Process:
* 1. Initialize the class with m and k values and an empty list to store the stream.
* 2. For addElement method, add the element to the stream.
* 3. For calculateMKAverage method, check if the stream has at least m elements.
* - If not, return -1.
* - Otherwise, get the last m elements, sort them, remove the smallest k and largest k elements, and calculate the average of the remaining elements using streams.
* - Return the average after flooring it.
*/
import java.util.*;
import java.util.stream.*;
public class MKAverage {
private int m, k;
private List<Integer> stream;
public MKAverage(int m, int k) {
this.m = m;
this.k = k;
this.stream = new ArrayList<>();
}
public void addElement(int num) {
stream.add(num);
}
public int calculateMKAverage() {
if (stream.size() < m) {
return -1;
}
List<Integer> lastMElements = stream.stream()
.skip(stream.size() - m)
.sorted()
.collect(Collectors.toList());
for (int i = 0; i < k; i++) {
lastMElements.remove(0); // Remove smallest k elements
lastMElements.remove(lastMElements.size() - 1); // Remove largest k elements
}
int sum = lastMElements.stream().mapToInt(Integer::intValue).sum();
return sum / lastMElements.size(); // Floor division
}
}
解释
方法:
该题解采用了三个有序列表(SortedList)和一个队列(deque)来维护数据流中的最后m个元素,并且实现了动态地维持这些元素中最小的k个、最大的k个和中间的m-2k个元素。每次添加新元素时,首先判断其应该插入哪个有序列表中,并且相应地更新这些列表和中间元素的和。当元素总数超过m时,从队列和相应的有序列表中移除最早的元素,并保持有序列表的平衡。计算MK平均值时,如果元素个数不足m,则返回-1;否则,返回中间元素和的整数除以中间元素的数量。
时间复杂度:
O(log m)
空间复杂度:
O(m)
代码细节讲解
🦆
如何确保在调整三个有序列表的大小时,他们始终保持正确的长度和元素顺序?
▷🦆
当从中间列表移动元素到上层或下层列表时,为何选择移动中间列表的首元素或尾元素,这种选择对平均值计算有何影响?
▷🦆
在删除元素时,如何处理存在于三个有序列表之一中的情况,特别是当相同的元素值可能属于不同列表时?
▷