您的位置:首页 > 其它

一个运行时间为nlgn的算法,能判断在集合S中是否有两数之和为x

2014-07-20 16:31 435 查看


先用归并排序对集合S中的整数进行排序,接着再用下面的子过程进行判断:

bool Func(int Array[], int first, int last, int x)
{
while (first < last)
{
if (Array[first] + Array[last] < x)
{
++first;
}
else
{
if (Array[first] + Array[last] > x)
{
--last;
}
else
{
return true;
}
}
}
return false;
}

显然判断过程的时间复杂度为n,结合归并排序的时间复杂度,容易得出整个算法满足题意的要求.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐