Describe a θ(nlgn)-time algorithm that, given a set S of n real numbers and another real number x, determines whether or not there exist two elements in S whose sum is exactly x.
Solution:
First, sort the set using any θ(nlgn)-time sorting algorithm.
Then for each real number a in set S, search if (x-a) exists in the set S using binary seach algorithm.
It's easy to show that this solution is a θ(nlgn)-time algorithm.
Solution:
First, sort the set using any θ(nlgn)-time sorting algorithm.
Then for each real number a in set S, search if (x-a) exists in the set S using binary seach algorithm.
It's easy to show that this solution is a θ(nlgn)-time algorithm.
本文介绍了一种在给定实数集合中寻找两数之和等于特定值x的算法。该算法首先对集合进行排序,然后对于集合中的每个元素a,使用二分查找判断x-a是否也在集合中。
5671

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



