首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >条件语句的时间复杂性

条件语句的时间复杂性
EN

Stack Overflow用户
提问于 2016-06-22 10:40:20
回答 2查看 3.1K关注 0票数 1

如何用条件语句计算时间复杂度,这些语句可能会或不会导致更高的结果?

例如:

代码语言:javascript
复制
for(int i = 0; i < n; i++){  
   //an elementary operation   
   for(int j = 0; j < n; j++){
       //another elementary operation  
       if (i == j){  
           for(int k = 0; k < n; k++){
               //yet another elementary operation
           }
       } else {
           //elementary operation
       }
   }
}

如果if -条件下的内容被逆转了呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-06-22 10:45:21

您的代码取O(n^2)。前两个循环采用O(n^2)运算。"k“循环接受O(n)操作,并被调用n次。给出了O(n^2)。代码的总复杂度为O(n^2) + O(n^2) = O(n^2)。

另一次尝试:

代码语言:javascript
复制
 - First 'i' loop runs n times.
 - Second 'j' loop runs n times. For each of is and js (there are n^2 combinations):
     - if i == j make n combinations. There are n possibilities that i==j, 
      so this part of code runs O(n^2).
     - if it's not, it makes elementary operation. There are n^2 - n combinations like that
       so it will take O(n^2) time.
 - The above proves, that this code will take O(n) operations.
票数 1
EN

Stack Overflow用户

发布于 2016-06-22 10:54:35

这取决于您正在执行的分析类型。如果您正在分析最坏情况复杂性,那么请考虑这两个分支中最复杂的部分。如果您正在分析平均情况复杂性,您需要计算进入一个分支或另一个分支的概率,并将每个复杂性乘以走这条路径的概率。

如果您更改了分支,只需切换概率系数。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37965609

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档