给定一个具有N个元素的未排序数组arr [] ,任务是找出线性时间复杂度的数组中位数。
例子:
Input: N = 5, arr[] = {4, 1, 2, 6, 5}
Output: 4
Explanation:
Since N = 5, which is odd, therefore the median is the 3rd element in the sorted array.
The 3rd element in the sorted arr[] is 4.
Hence the median is 4.
Input: N = 8, arr[] = {1, 3, 4, 2, 6, 5, 8, 7}
Output: 4.5
Explanation:
Since N = 8, which is even, therefore median is the average of 4th and 5th element in the sorted array.
The 4th and 5th element in the sorted array is 4 and 5 respectively.
Hence the median is (4+5)/2 = 4.5.
方法:想法是在C++ STL中使用nth_element()函数。
- 如果数组中元素的数量为奇数,请使用nth_element()函数找到第(N / 2)个元素,如下所示,然后索引(N / 2)的值为给定数组的中位数。
nth_element(arr.begin(), arr.begin() + N/2, arr.end())
- 否则,使用nth_element()函数找到第(N / 2)个和第((N – 1)/ 2)个元素,如下所示,并找到索引(N / 2)和((N – 1) / 2)是给定数组的中位数。
nth_element(arr.begin(), arr.begin() + N/2, arr.end())
nth_element(arr.begin(), arr.begin() + (N – 1)/2, arr.end())
下面是上述方法的实现:
// C++ program for the above approach
#include
using namespace std;
// Function for calculating
// the median
double findMedian(vector a,
int n)
{
// If size of the arr[] is even
if (n % 2 == 0) {
// Applying nth_element
// on n/2th index
nth_element(a.begin(),
a.begin() + n / 2,
a.end());
// Applying nth_element
// on (n-1)/2 th index
nth_element(a.begin(),
a.begin() + (n - 1) / 2,
a.end());
// Find the average of value at
// index N/2 and (N-1)/2
return (double)(a[(n - 1) / 2]
+ a[n / 2])
/ 2.0;
}
// If size of the arr[] is odd
else {
// Applying nth_element
// on n/2
nth_element(a.begin(),
a.begin() + n / 2,
a.end());
// Value at index (N/2)th
// is the median
return (double)a[n / 2];
}
}
// Driver Code
int main()
{
// Given array arr[]
vector arr = { 1, 3, 4, 2,
7, 5, 8, 6 };
// Function Call
cout << "Median = "
<< findMedian(arr, arr.size())
<< endl;
return 0;
}
Median = 4.5
时间复杂度: O(N)
辅助空间复杂度: O(1)