C++ 数组的第k个最小元素,不满足所需时间复杂度的中位数
我正在尝试向在线法官提交一个解决方案,以找到数组中第k个最小元素。 我选择了最有效的快速算法,但在线法官仍然抛出了一个时间限制错误。有更快的算法吗 这是一个名为中值的算法。 提交的代码:C++ 数组的第k个最小元素,不满足所需时间复杂度的中位数,c++,C++,我正在尝试向在线法官提交一个解决方案,以找到数组中第k个最小元素。 我选择了最有效的快速算法,但在线法官仍然抛出了一个时间限制错误。有更快的算法吗 这是一个名为中值的算法。 提交的代码: #include <iostream> //#include <cmath> #include <climits> //#include <string> #include <algorithm> using namespace std; int
#include <iostream>
//#include <cmath>
#include <climits>
//#include <string>
#include <algorithm>
using namespace std;
int partition(int arr[], int l, int r, int x)
{
// Search for x in arr[l..r] and move it to end
int i;
for (i = l; i < r; i++)
if (arr[i] == x)
break;
swap(arr[i], arr[r]);
// Standard partition algorithm
i = l;
for (int j = l; j <= r - 1; j++)
{
if (arr[j] <= x)
{
swap(arr[i], arr[j]);
i++;
}
}
swap(arr[i], arr[r]);
return i;
}
// A simple function to find median of arr[]. This is called
// only for an array of size 5 in this program.
int findMedian(int arr[], int n)
{
sort(arr, arr + n); // Sort the array
return arr[n / 2]; // Return middle element
}
int kthSmallest(int arr[], int l, int r, int k)
{
if (k > 0 && k <= r - l + 1)
{
int i, n = r - l + 1;
int *median = new int[(n + 4) / 5];
for (i = 0; i < n / 5; i++) {
median[i] = findMedian(arr + l + i * 5, 5);
}
if (i * 5 < n) //For last group with less than 5 elements
{
median[i] = findMedian(arr + l + i * 5, n % 5);
i++;
}
int medOfMed = (i == 1) ? median[i - 1] :
kthSmallest(median, 0, i - 1, i / 2);
int pos = partition(arr, l, r, medOfMed);
if (pos - l == k - 1)
return arr[pos];
if (pos - l > k - 1)
return kthSmallest(arr, l, pos - 1, k);
return kthSmallest(arr, pos + 1, r, k - pos + l - 1);
}
return INT_MAX;
}
// It searches for x in arr[l..r], and partitions the array
// around x.
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n, k;
cin >> n >> k;
int *a = new int[n];
for (int i = 0; i < n; i++)
cin >> a[i];
cout << kthSmallest(a, 0, n - 1, k);
delete[] a;
return 0;
}
#包括
//#包括
#包括
//#包括
#包括
使用名称空间std;
整数分区(整数arr[],整数l,整数r,整数x)
{
//在arr[l..r]中搜索x并将其移动到末尾
int i;
对于(i=l;in>>k;
int*a=新的int[n];
对于(int i=0;i>a[i];
cout在中有一个函数std::nth_元素,可以用来快速查找数组的中值。附带问题:我一直在看freopen(“input.txt”,“r”,stdin)
晚了很多,但也有几次搞砸了。他们从处理cin
和cout
中得到了什么好处,而这是他们从“正常”打开文件流中得不到的方法?仅供参考,已经有一个std::partition
算法函数。不需要自己编写。我不知道是哪个头。请告诉我算法的名称。我省略了排序,仍然有时间限制错误。对不起,头是#include
,算法的名称是std::n\u元素。我仍然不明白,请注意如果你想帮助的话,请使用se。如果你阅读了关于上述函数的文档,你将学会如何使用它来确定数组的中位数是快的。我真的不知道如何将这些知识应用到你正在解决的问题上。