【问题标题】:Time complexity of simple if else statement简单 if else 语句的时间复杂度
【发布时间】:2020-11-24 22:07:57
【问题描述】:

我是新手,无法理解 if else 语句的时间复杂度。我在网上读到 if-else 的时间复杂度是以最大值和最小值给出的。

根据我的理解,max 和 min 都是 O(1),但有些网站共享其他内容,我无法理解。谢谢。

Function copy(number)
  If number == 3
     console.log("number is 3");
  Else
     console.log("number is not 3");

【问题讨论】:

  • 它是 O(1)。我从未听说过 if else 语句的时间复杂度。不过,您可以通过将最可能的结果作为第一个 if 条件来加快该过程。只有多次测试条件才重要。如果其他网站有其他分享,请分享出处,其他人也可以看看
  • 这能回答你的问题吗? Algorithm complexity: if/else under for loop
  • @John 这些是我读到的笔记,它说复杂度应该是 O(1) 和 O(n) [链接] (pages.cs.wisc.edu/~vernon/cs367/notes/…*%20M))。跨度>

标签: javascript time-complexity


【解决方案1】:

为了清楚起见,link you posted in the comment 说:

if-then-else 语句

if (condition) {
    sequence of statements 1
}
else {
    sequence of statements 2
}

在这里,要么执行序列 1,要么执行序列 2。 因此,最坏情况的时间是两者中最慢的 可能性:最大(时间(序列 1),时间(序列 2))。例如, 如果序列 1 是 O(N) 并且序列 2 是 O(1) 的最坏情况时间 整个 if-then-else 语句将是 O(N)。

这意味着您考虑了 序列 之一的最差时间复杂度,而不是 if-else-statement 本身。

让我再举一个例子

function foo(){
  if (bar) {
    return 'bar'; // O(1)
  } else {
    return someArray.map((a) => a+1); // O(n)
  }
}

【讨论】:

  • 非常感谢。现在,我能够理解为什么采用 O(n) 的概念了。
猜你喜欢
  • 2020-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
  • 2020-06-24
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
相关资源
最近更新 更多