大O在有限的,固定大小的设置可能值 [英] Big O for a finite, fixed size set of possible values

查看:141
本文介绍了大O在有限的,固定大小的设置可能值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<一个href="http://stackoverflow.com/questions/12305028/java-what-is-the-best-way-to-find-first-duplicate-character-in-a-string">This 引起了一些混乱,有关在各种答案中提出的算法是否为O(1)或O(N)。

This question triggered some confusion and many comments about whether the algorithms proposed in the various answers are O(1) or O(n).

让我们用一个简单的例子来说明这两种观点:

Let's use a simple example to illustrate the two points of view:

我们希望找到一个长 X ,使得 A * X + B = 0 ,其中 A B 是已知的,非空多头。

we want to find a long x such that a * x + b = 0, where a and b are known, non-null longs.

  • 在一个明显的O(1)算法中的 X = - B / A
  • 在慢得多的算法中会包括在测试中每一个可能的长期价值,这将是平均慢2 ^ 63次。

时的第二个算法O(1)或O(N)?

Is the second algorithm O(1) or O(n)?

psented的链接问题的争论$ P $是:

The arguments presented in the linked questions are:

  • it is O(n) because in the worst case you need to loop over all possible long values
  • it is O(1) because its complexity is of the form c x O(1), where c = 2^64 is a constant.

虽然我明白的说法说,这是O(1),感觉违反直觉。

Although I understand the argument to say that it is O(1), it feels counter-intuitive.

PS:我加作为原问题是在Java中,但这个问题是语言无关。

ps: I added java as the original question is in Java, but this question is language-agnostic.

推荐答案

的复杂性是唯一相关,如果有一个变量N所以,问题是没有意义的原样。如果问题是:

The complexity is only relevant if there is a variable N. So, the question makes no sense as is. If the question was:

一个慢得多算法中会包括在测试中每一个可能的价值在区域N的值,这将是大约N倍速度较慢的平均水平。

A much slower algo would consist in testing every possible value in a range of N values, which would be about N times slower on average.

时的第二个算法O(1)或O(N)?

Is the second algorithm O(1) or O(N)?

那么答案将是:这个算法是O(N)

Then the answer would be: this algorithm is O(N).

这篇关于大O在有限的,固定大小的设置可能值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆