打表:
总体就是将反复需要的结果,或者算法较为复杂,可以找到规律可以直接得到一小部分结果,将这些数值事先存放在数组中,用空间换时间。
因为可能有些算法题,在写的时候我们会超时。
活用递推:
寻找隐藏在题目中的规律。
随机选择算法:
暴力法是全局排序可以解决问题,但全局排序会浪费很多时间,我们只需要找到其中一个数即可。随机快速排序,找到第k个大的数。
题目训练:
求第k大的数
(Kth.pas/c/cpp)
给定一个长度为n(1≤n≤1,000,000)的无序正整数序列,以及另一个数k(1≤k≤1,000,000)(关于第k大的数:例如序列{1,2,3,4,5,6}中第3大的数是4。)
输入
第一行两个正整数m,n。
第二行为n个正整数。
输出
第k大的数。
样例输入 Copy
6 3 1 2 3 4 5 6
样例输出 Copy
4
代码:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include <fstream>
#include <string>
#include <cmath>
#include <algorithm>
#include <queue>
#include <ctime>
using namespace std;
int BinaryFindK(int a[], int L, int R,int K)
{
int pos = round((double)rand() / RAND_MAX * (R - L)) + L,tmp ,TL = L,TR = R;#快速排序使用随机中间值,效率更高
tmp = a[pos]; a[pos] = a[TL];
while (TL < TR)
{
while (TL < TR && a[TR] <= tmp) TR--;
a[TL] = a[TR];
while (TL < TR&&a[TL] >= tmp) TL++;
a[TR] = a[TL];
}
a[TL] = tmp;
if (TL == K)
return a[TL];
else if (TL > K)
return BinaryFindK(a, L, TL - 1, K);
else return BinaryFindK(a, TL + 1, R, K);
}
int main()
{
#ifdef _DEBUG
freopen("data.txt", "r+", stdin);
//fstream cin("data.txt");
#endif // _DEBUG
const unsigned int MaxN = 100010;
bool flag[MaxN];
int Data[MaxN];
srand((unsigned int)time(NULL));
int K, n, tmp, Num = 0;
while(~scanf("%d %d", &n, &K))
{
for (int i = 0; i < n; ++i)
{
scanf("%d", &tmp);
if (!flag[tmp])
{
Data[Num++] = tmp;
flag[tmp] = true;
}
}
//sort(Data, Data + Num,cmp);
//printf("%d\n", Data[K-1]);
int res = BinaryFindK(Data, 0, Num - 1, K - 1);
printf("%d", res);
}
#ifdef _DEBUG
//cin.close();
#ifndef _CODEBLOCKS
system("pause");
#endif // !_CODEBLOCKS
#endif // _DEBUG
return 0;
}