题目来源:码蹄集
C++代码实现demo1(官方答案版):
这个是可以通过测试的
#include <iostream>
#include <cstring>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
multiset<int> s;
// 定义左指针和右指针
multiset<int>::iterator l = s.end(), r = s.end();
// 初始指向end
void addNum(int num) {
int n = s.size();
s.insert(num);
// 插入第一个元素
if(n == 0){
l = r = s.begin();
}
// 元素个数由奇数个变为偶数个
else if(n & 1){
if(num < *l){
l--;
}
else{
r++;
}
}
// 元素个数由偶数个变为奇数个
else{
if(num > *l && num < *r){
l++;
r--;
}
else if(num >= *r){
l++;
}
else{
r--;
l = r;
}
}
}
double findMedian() {
return (*l + *r) / 2.0;
}
int main() {
int n;
vector<int> num_list;
cin >> n;
while(n--) {
getchar();
char op = getchar();
int num;
if(op == '?')
cout << findMedian() << endl;
else if(op == '+') {
cin >> num;
addNum(num);
}
}
return 0;
}
Python代码实现demo2(会超时!):
这个是我最开始写的解决办法,很基础易懂,但是算法复杂度高,能通过码蹄集给的一个测试用例,但在接下来的测试中会超时。
def add_num(a,list):
list.append(int(a))
def search_mid_num(list):
if len(list) % 2 == 0:
print((list[(len(list)//2)-1] + list[len(list)//2]) / 2.0)
else:
print(list[len(list)//2])
list0 = []
list1 = []
n = int(input())
for i in range(n):
list0.append(input())
for j in list0:
if j.startswith("+"):
add_num(j.strip("+ "), list1)
else:
list = sorted(list1)
search_mid_num(list1)
Python代码实现demo3(报答案错误):
这里使用了 Python 内置的堆数据结构 heapq,能够有效地维护一个动态的有序数列,并且支持快速地查找中位数。
这段代码也是能通过给出的测试用例,但是接下来就说答案错误了,也不知道错哪了,也看不到其他的测试用例,我实在想不出来了,如果有能看出来的大佬麻烦指点一下我。
import heapq
list1 = []
list0 = []
n = int(input())
for i in range(n):
x = input()
if x.startswith("+"):
heapq.heappush(list1, int(x.strip("+ ")))
else:
if len(list1) % 2 == 0:
mid = (list1[len(list1) // 2 - 1] + list1[len(list1) // 2]) / 2.0
else:
mid = list1[len(list1) // 2]
list0.append(mid)
for j in list0:
print(j)
Python代码实现demo4(报答案错误):
这段代码也是一样,能通过给出的测试用例但是接下来就报答案错误
import heapq
def add_num(a, min_heap, max_heap):
try:
num = int(a)
if len(max_heap) == len(min_heap):
heapq.heappush(max_heap, -num)
else:
heapq.heappush(min_heap, num)
if len(max_heap) > 0 and len(min_heap) > 0 and -max_heap[0] > min_heap[0]:
max_top = -heapq.heappop(max_heap)
min_top = heapq.heappop(min_heap)
heapq.heappush(max_heap, -min_top)
heapq.heappush(min_heap, max_top)
except ValueError:
print(f"Invalid input: {a} is not a valid integer")
def get_mid_num(min_heap, max_heap):
if len(max_heap) == len(min_heap):
return (-max_heap[0] + min_heap[0]) / 2.0
else:
return -max_heap[0]
list0 = []
min_heap = []
max_heap = []
n = int(input())
for i in range(n):
list0.append(input())
for j in list0:
if j.startswith("+"):
add_num(j.strip("+ "), min_heap, max_heap)
else:
print(get_mid_num(min_heap, max_heap))