[英]How to solve this in less than O(N)?
I have an array of sorted (ascending order) elements as input.我有一个排序(升序)元素的数组作为输入。 I want to find out whether these elements make a series in which each current element is divisible by all the elements that came before it.我想找出这些元素是否构成一个系列,其中每个当前元素都可以被它之前的所有元素整除。 This is an obvious solution to this problem in O(n) time that I could think of:这是我能想到的 O(n) 时间内这个问题的明显解决方案:
bool CheckArray(int arr[], int no_of_elements)
{
if (no_of_elements == 1)
return true;
for (int i = 1; i < no_of_elements; i++)
if (arr[i] % arr[i - 1] != 0)
return false;
return true;
}
Example 1: Input: 3 6 9 12 Output: False示例 1:输入:3 6 9 12 输出:假
Example 2: Input: 3 6 12 Output: True示例 2:输入:3 6 12 输出:真
Is there any way to do it in less than O(n) time though?有没有什么办法可以在小于 O(n) 的时间内做到这一点? If yes, how?如果是,如何?
It is not possible to do it in better than O(n).不可能以比 O(n) 更好的方式做到这一点。
Each element could have a value that changes the solution from true to false.每个元素都可以有一个值,将解决方案从 true 更改为 false。 So, you need to do at least an operation on each element, to check it.所以,你至少需要对每个元素做一个操作,来检查它。
As such you'll have at least O(n).因此,您将至少拥有 O(n)。
Clearly you need an O(N) traversal in order to yield true
.显然,您需要 O(N) 遍历才能产生true
。
The optimisation you can make is to yield a false
as soon as possible.您可以进行的优化是尽快产生false
。
I conject (and think the proof would be hard but is true if the numbers are arithmetically distributed) that adjacent larger number pairs ( a , b ) are less likely to be of the form ( a , na ) for integral n than smaller numbers.我推测(并认为证明会很困难,但如果数字是算术分布的,则证明是正确的)相邻的较大数字对( a , b )比较小的数字更不可能是整数n的形式( a , na )。 Therefore you could yield a false
more quickly by considering the larger numbers first.因此,您可以通过首先考虑较大的数字来更快地产生false
。 In other words, running the loop from the last to the first element may well end up being statistically quicker.换句话说,从最后一个元素到第一个元素运行循环很可能最终会在统计上更快。 You'd have to profile on the typical number series that are presented to your function.您必须对呈现给您的函数的典型数字系列进行概要分析。
By the way, your preamble顺便说一下,你的序言
if (no_of_elements == 1)
return true;
is redundant.是多余的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.