题目描述:
示例:
题目分析:
- 返回有序元素列表的中位数
- 如果有序元素列表为奇数,则返回中间位置的元素
- 如果有序元素列表为偶数,则返回中间两个元素之和再除以2的值
思路:
代码实现:
class MedianFinder {
PriorityQueue<Integer> left = new PriorityQueue<>((a, b) -> b-a);
PriorityQueue<Integer> right = new PriorityQueue<>((a, b) -> a-b);
public MedianFinder() {
}
public void addNum(int num) {
int leftLen = left.size();
int rightLen = right.size();
if (leftLen == rightLen) {
if (right.isEmpty() || num <= right.peek()) {
left.add(num);
} else {
left.add(right.poll());
right.add(num);
}
} else {
if (left.peek() <= num) {
right.add(num);
} else {
right.add(left.poll());
left.add(num);
}
}
}
public double findMedian() {
int leftLen = left.size();
int rightLen = right.size();
if (leftLen == rightLen) {
return (left.peek() + right.peek()) / 2.0;
} else {
return left.peek();
}
}
}