程序员面试金典——18.9实时中位数
程序员文章站
2024-02-14 11:51:28
...
程序员面试金典——18.9实时中位数
Solution1:我的答案。利用排序,比较弱智。。
class Middle {
public:
vector<int> getMiddle(vector<int> A, int n) {
// write code here
vector<int> res;
if (n <= 0)
return res;
auto iter1 = A.begin(), iter2 = ++A.begin();
for (; iter2 <= A.end(); iter2++) {
sort(iter1, iter2);
res.push_back(A[(iter2 - iter1 - 1) / 2]);//注意准确计算下标
}
return res;
}
};
Solution2:利用优先队列priority_queue,说实话还是第一次用呢~~
此题思路如下图所示:
利用priority_queue自动排序了
关于priority_queue介绍的博客:
[1]https://blog.csdn.net/pzhu_cg_csdn/article/details/79166858
[2]http://www.cplusplus.com/reference/queue/priority_queue/
class Middle {
public:
vector<int> getMiddle(vector<int> A, int n) {
// write code here
priority_queue<int, vector<int>, less<int> > small;
priority_queue<int, vector<int>, greater<int> > big;
vector<int> ans;
for (int i = 0; i < A.size(); ++i) {
if (small.empty() || A[i] <= small.top())
small.push(A[i]);
else
big.push(A[i]);
if (small.size() == big.size() + 2) {
big.push(small.top());
small.pop();
}
else if (small.size() == big.size() - 1) {
small.push(big.top());
big.pop();
}
ans.push_back(small.top());
}
return ans;
}
};
Solution3:
利用最大堆和最小堆实现,其思想和用priority_queue差不多,但是代码却麻烦了好多。。。。还是优先队列好啊
关于最大堆和最小堆的介绍:
[1]https://blog.csdn.net/guoweimelon/article/details/50904346
关于push_heap和pop_heap的介绍
[1]https://blog.csdn.net/fuyufjh/article/details/47144869
class Middle {
public:
vector<int> getMiddle(vector<int> A, int n) {
// write code here
vector<int> maxheap;
vector<int> minheap;
vector<int> re;
for (int i = 0; i < n; ++i) {
if (maxheap.size() == minheap.size()) {
if (minheap.size() > 0 && minheap.front() < A[i]) {
pop_heap(minheap.begin(), minheap.end(), greater<int>());
maxheap.push_back(minheap.back());
push_heap(maxheap.begin(), maxheap.end(), less<int>());
minheap.pop_back();
minheap.push_back(A[i]);
push_heap(minheap.begin(), minheap.end(), greater<int>());
}
else {
maxheap.push_back(A[i]);
push_heap(maxheap.begin(), maxheap.end(), less<int>());
}
}
else {
if(maxheap.front() > A[i]) {
pop_heap(maxheap.begin(), maxheap.end(), less<int>());
minheap.push_back(maxheap.back());
push_heap(minheap.begin(), minheap.end(), greater<int>());
maxheap.pop_back();
maxheap.push_back(A[i]);
push_heap(maxheap.begin(), maxheap.end(), less<int>());
}
else {
minheap.push_back(A[i]);
push_heap(minheap.begin(), minheap.end(), greater<int>());
}
}
re.push_back(maxheap.front());
}
return re;
}
};
推荐阅读