给定一个具有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)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live