#include <vector>
#include <algorithm>
#include <functional> // For greater<int>( )
#include <iostream>
#include <time.h>
#include <set>
using namespace std;
#define BIG_ARR_SIZE 10000000
#define RES_ARR_SIZE 10000
template< class T>
void solution_2( T BigArr[], T ResArr[] )
{
memcpy(ResArr,BigArr,sizeof(T)*RES_ARR_SIZE);
std::sort( ResArr, ResArr + RES_ARR_SIZE, std::greater<T>() );
int MinElemIdx = RES_ARR_SIZE -1;
int ZoneBeginIdx = MinElemIdx;
for(int i=RES_ARR_SIZE;i<BIG_ARR_SIZE;++i)
{
if(BigArr[i]>ResArr[MinElemIdx])
{
ResArr[MinElemIdx] = BigArr[i];
if((MinElemIdx==ZoneBeginIdx))
--ZoneBeginIdx;
if(ZoneBeginIdx<9500)
{
//std::sort( ResArr, ResArr + RES_ARR_SIZE, std::greater<int>() );
//ZoneBeginIdx=MinElemIdx=RES_ARR_SIZE - 1;
std::sort( ResArr + 9500, ResArr + RES_ARR_SIZE, std::greater<int>() );
std::merge(ResArr, ResArr + 9500, ResArr + 9500, ResArr + RES_ARR_SIZE, BigArr, std::greater<int>() );
ZoneBeginIdx=MinElemIdx=RES_ARR_SIZE - 1;
memcpy( ResArr, BigArr, sizeof(T) * RES_ARR_SIZE );
}
else
{
MinElemIdx = ZoneBeginIdx;
for(int j=MinElemIdx+1;j<RES_ARR_SIZE;++j)
{
if(ResArr[MinElemIdx]>ResArr[j])
MinElemIdx=j;
}
}
}
}
}
void mysolution(int a[],int b[])
{
set<int> s;
for(int i=0;i<BIG_ARR_SIZE;++i)
{
if(s.size()<RES_ARR_SIZE)
s.insert(a[i]);
else if(*s.begin()<a[i])
{
s.insert(a[i]);
s.erase(*s.begin());
}
}
b[0]=*s.begin();
b[RES_ARR_SIZE-1] =*s.rbegin();
}
char *mystrcat(char *s,char *t)
{
assert(s!=NULL && t!=NULL);
char *address = s; // 2分
while(*s++)
{
}
s--;
while(*s++=*t++)
{
}
return address;
}
char* GetMemory(char **p, int num)
{
*p = (char *)malloc(num);
return *p;
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
str= strcpy(str, "hello");
printf(str);
free(str);
}
void main()
{
int *a=new int[BIG_ARR_SIZE];
int b[RES_ARR_SIZE];
for(int i=0;i<BIG_ARR_SIZE;++i)
{
a[i]=rand();
}
clock_t t_start;
clock_t t_end;
/*
t_start = clock();
mysolution(a,b);
t_end = clock();
printf("time: %.3f s/n", (double)(t_end-t_start)/CLOCKS_PER_SEC);
cout<<b[0]<<endl;
cout<<b[RES_ARR_SIZE-1]<<endl;
*/
/*
t_start = clock();
nth_element(a,a+RES_ARR_SIZE,a+BIG_ARR_SIZE,std::greater<int>());
t_end = clock();
printf("time: %.3f s/n", (double)(t_end-t_start)/CLOCKS_PER_SEC);
std::sort(a,a+RES_ARR_SIZE,std::greater<int>());
cout<<"min="<<a[0]<<" max="<<a[RES_ARR_SIZE-1]<<endl;
*/
t_start = clock();
solution_2(a,b);
t_end = clock();
printf("time: %.3f s/n", (double)(t_end-t_start)/CLOCKS_PER_SEC);
std::sort(b,b+RES_ARR_SIZE,std::greater<int>());
cout<<b[0]<<endl;
cout<<b[RES_ARR_SIZE-1]<<endl;
char f[100]="hello ";
char g[100]="kity";
char *p;
//cout<<strlen(mystrcat(f,g));
Test();
delete[]a;
getchar();
}
4205

被折叠的 条评论
为什么被折叠?



