# 查找集合中两个最大的元素

———Polyaand Szego[1927]

vector<int>& get2max(int *arr,int len,int &max,vector<int> &candidate)
{
if(len == 1)
{
max = arr[len-1];
return candidate;
}
else if(len == 2)
{
if(arr[len-2] > arr[len-1])
{
max = arr[len-2];
candidate.push_back(arr[len-1]);
return candidate;
}
else
{
max = arr[len-1];
candidate.push_back(arr[len-2]);
return candidate;
}

}

int p1,q1;
vector<int> &candidate1 = *new vector<int>;
vector<int> &candidate2 = *new vector<int>;

//P子集中的候选者
candidate1 = get2max(arr,len/2,p1,candidate1);

//Q子集中候选者
candidate2 = get2max(arr+len/2,len - len/2,q1,candidate2);

if(p1 > q1)
{
max = p1;
candidate1.push_back(q1);
delete &candidate2;
return candidate1;
}
else if(p1 == q1)
{
max = p1;
candidate1.clear();
candidate2.clear();
candidate1.push_back(p1);
delete &candidate2;
return candidate1;
}
else
{
max = q1;
candidate2.push_back(p1);
delete &candidate1;
return candidate2;
}
}

void get2max(int *arr, int len)
{
int m1,m2;
vector<int> can;
can = get2max(arr,len,m1,can);

vector<int>::iterator i = can.begin();
m2 = can[0];
for(++i;i!=can.end(); ++i)
{
if(*i > m2)
m2 = *i;
}

cout<<"first maximum:  "<<m1<<endl;
cout<<"second maximum:  "<<m2<<endl;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120