简单if else语句的时间复杂度

Time complexity of simple if else statement

我是初学者,无法理解 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");

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

if-then-else 语句

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

Here, either sequence 1 will execute, or sequence 2 will execute. Therefore, the worst-case time is the slowest of the two possibilities: max(time(sequence 1), time(sequence 2)). For example, if sequence 1 is O(N) and sequence 2 is O(1) the worst-case time for the whole if-then-else statement would be O(N).

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

再举个例子

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