English 中文(简体)
在一个预先排序的数组中,查找是否有两个元素的和等于某个特定的值。
原标题:Finding if two elements in a pre-sorted array sum to equal a certain value
  • 时间:2010-02-05 01:27:09
  •  标签:
  • algorithm

我正在做一道作业题,但是在创建一个O(n*logn)的解决方案方面遇到了一些困难。我需要编写一个函数,该函数接受一个已预排序的数组和一个要搜索的值。接下来,我需要找到数组中是否有任何两个元素的总和等于该值。

我需要创建O(n)和O(n * logn)算法。

O(n)很容易创建;然而,我在创建O(n*logn)算法时遇到了困难,没有添加一些不实际有助于解决问题的不必要代码。如果有人可以给我一些提示,我将不胜感激。

最佳回答

从第一个元素开始,顺序前进。在此过程中,使用二分搜索查找第二个元素。

问题回答

由于它们是预先排序的,您可以使用二进制搜索和线性搜索。





相关问题
How to add/merge several Big O s into one

If I have an algorithm which is comprised of (let s say) three sub-algorithms, all with different O() characteristics, e.g.: algorithm A: O(n) algorithm B: O(log(n)) algorithm C: O(n log(n)) How do ...

Grokking Timsort

There s a (relatively) new sort on the block called Timsort. It s been used as Python s list.sort, and is now going to be the new Array.sort in Java 7. There s some documentation and a tiny Wikipedia ...

Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Enumerating All Minimal Directed Cycles Of A Directed Graph

I have a directed graph and my problem is to enumerate all the minimal (cycles that cannot be constructed as the union of other cycles) directed cycles of this graph. This is different from what the ...

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签