I'm trying to solve a programming challenge where I have to find the median of given subarrays of an array. I have used std::vector
's n_th element
for this. But the evaluator fails some test cases as "time limit exceeded".
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
/*
In
6
2 4 5 3 1 6
3
1 6
2 4
3 3
Out
3
4
5
*/
int get_ceil(int length)
{
if (length % 2 == 0)
{
return length/2;
}
else
{
return (length+1)/2;
}
}
int get_median_of_subarray(std::vector<int> & full_array, int lo, int hi)
{
std::vector<int>::const_iterator begin = full_array.begin() + lo;
std::vector<int>::const_iterator end = full_array.begin() + hi + 1;
std::vector<int> sub_array(begin, end);
int median_pos = get_ceil(hi - lo + 1);
std::nth_element (sub_array.begin(), sub_array.begin() + median_pos -1, sub_array.end());
return sub_array[median_pos - 1];
}
int main()
{
ios_base::sync_with_stdio(false);
int array_size = 0;
std::vector<int> input_array;
cin >> array_size;
for(int i = 0; i < array_size; i++)
{
int x;
cin >> x;
input_array.push_back(x);
}
int query_size = 0;
cin >> query_size;
int lo = 0;
int hi = 0;
for(int i = 0; i < query_size; i++)
{
cin >> lo >> hi;
std::cout << get_median_of_subarray(input_array, --lo, --hi) << std::endl;
}
return 0;
}
full_array
should be a reference-to-const, it isn't modified inside your function. This just clarifies your code a bit. The median of [2, 10] is 6, which your algorithm ignores. Since you get a timeout and not a test failure, I guess that all this is just about odd-sized sequences. \$\endgroup\$get_ceil()
is a bit overcomplicated. Iflength = 3
,(length + 1) / 2 = 2
. Iflength = 4
,(length + 1) / 2 = 2
, due to integer division. C++ doesn't round but truncate the result. Therefore, you can alwaysreturn (length + 1) / 2;
. I'd also call thisget_half_ceil()
, because that's closer to what it does. \$\endgroup\$<algorithm>
'sstd::nth_element()
on a vector. The distinction is important, because the standard algorithms are written to be generic, and usable on all kinds of container (and, in some cases on things that aren't containers). \$\endgroup\$