简体   繁体   English

最好和最坏的情况

[英]best and worst case

I need help to find best case and worst case of this code with explanation.我需要帮助来找到这段代码的最佳情况和最坏情况,并附上解释。 I think worst case is O(n).我认为最坏的情况是 O(n)。

public static boolean adjacentDuplicates(int[] a) {
  for (int i = 0; i < a.length-1; i++)
    if (a[i] == a[i+1]) return true;
  return false;
}

The best case is in the first comparison return the value.最好的情况是在第一次比较中return值。 Hence, if a[0] == a[1] the time complexity is \\Theta(1) .因此,如果a[0] == a[1]时间复杂度为\\Theta(1) And the worse is the comparison will not be satisfied up to the end of the loop.更糟糕的是,直到循环结束都不会满足比较。 Hence, the worst-case complexity is \\Theta(n) (that n is the length of the input array a ).因此,最坏情况的复杂度是\\Theta(n) (即n是输入数组a的长度)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM