-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMedian.cpp
More file actions
43 lines (36 loc) · 791 Bytes
/
Median.cpp
File metadata and controls
43 lines (36 loc) · 791 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
Given a list of numbers, can you find the median?
Input
There will be two lines of input:
n – the size of the array
ar – n numbers that makes up the array
1 ≤ n ≤ 1000001
n is odd
-100000 ≤ x ≤ 100000, x ∈ ar
Output
Output one integer, the median.
#priority-queue #heap
*/
#include<iostream>
#include<queue>
using namespace std;
int main() {
int n;
cin >> n;
int len = n / 2 + 1;
priority_queue<int, vector<int>, greater<int> > pq;
for (int i=0; i < n; i++) {
int tmp;
cin >> tmp;
if ((int)pq.size() >= len) {
if (tmp > pq.top()){
pq.pop();
pq.push(tmp);
}
} else {
pq.push(tmp);
}
}
cout << pq.top() << endl;
return 0;
}