问题:
难度:hard
说明:
题目会不断输入数字元素,然后查询这些数字的中间数是什么,如果输入的长度是奇数,那么就是 A,如果是偶数,就是 (A + B) / 2,中间两个数相加除 2。
题目连接:https://leetcode.com/problems/find-median-from-data-stream/
输入范围:
-105 <= num <= 105
- There will be at least one element in the data structure before calling
findMedian
. - At most
5 * 104
calls will be made toaddNum
andfindMedian
.
输入案例:
Input
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
Output
[null, null, null, 1.5, null, 2.0]
Explanation
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1); // arr = [1]
medianFinder.addNum(2); // arr = [1, 2]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3); // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0
我的代码:
偷懒想法就是用 TreeMap,自带堆排序的数据结构,然后每次元素进来都进行排序,我使用两个堆,一个是最大堆,作为 从最小到中间 的集合,另一个最小堆,作为 从中间到最大 集合。
当然,想要更快就自己写数组建数据结构,还是因为偷懒所以直接用语言提供的 api。
然后因为会输入重复元素,Map 需要另外记录长度,我设置 最小堆长度 <= 最大堆长度 < 最小堆长度 + 2,如果发现长度超出了就马上调整堆元素即可。
Java:
class MedianFinder {
int smallSize = 0, bigSize = 0;
TreeMap<Integer,Integer> small = new TreeMap<Integer,Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
TreeMap<Integer,Integer> big = new TreeMap<Integer,Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
public MedianFinder() {
}
public void addNum(int num) {
if(small.isEmpty()) {
small.put(num, 1); smallSize ++; return;
}
if(num > small.firstKey()) {
big.put(num, big.getOrDefault(num, 0) + 1);
bigSize ++;
} else {
small.put(num, small.getOrDefault(num, 0) + 1);
smallSize ++;
}
if(bigSize > smallSize) {
swapMap(big, small);
bigSize --; smallSize ++;
} else if(smallSize > bigSize + 1) {
swapMap(small, big);
bigSize ++; smallSize --;
}
}
public double findMedian() {
return smallSize > bigSize ? small.firstKey() : (double)(small.firstKey() + big.firstKey()) / 2;
}
public void swapMap(TreeMap<Integer, Integer> o1, TreeMap<Integer, Integer> o2) {
Map.Entry<Integer, Integer> e = o1.firstEntry();
int k = e.getKey(), v = e.getValue();
if(v != 1) {
o1.put(k, v - 1);
} else {
e = o1.pollFirstEntry();
}
o2.put(k, o2.getOrDefault(k, 0) + 1);
}
}