algorithm - 计算和分析运行时
问题描述
public static long Compute(int x){
long count = 0;
if(x==1)
return count=1;
else if(x==3)
for(int i =0;i<x;i++){
count+=i;
}
else if (x==5)
for(int j=0;j<x;j++)
for(int k=0;j<=x;k++)
return +=(i*j);
}
}
return result;
}
我试图了解如何解决每个语句以制定运行时 T(n)。我有 2 个 if 语句和一个 for 循环和一个嵌套的 for 循环。我的答案是 O(n^2)。
解决方案
f = O(g) 表示存在 N 和 c,因此 n>N 意味着 f(n) <= c * g(n)。(我假设 f 和 g 是非负的)。
对于 x>5,代码需要恒定的时间。所以它是O(1)。
推荐阅读
- python - 访问docker内部python应用启动的UI界面
- javascript - 多次请求删除和获取节点
- scala - 多项目 sbt 组装问题
- python - 在加入时向 Discord 服务器所有者发送消息
- r - 为什么 deparse(substitute(x)) 不选择“x”的名称
- ios - 应用启动时更改 tabbarindex 或 setviewcontroller
- java - Java-Firebase 连接不起作用
- dictionary - 使用 Elixir 中的模式匹配获取特定键和映射的其余部分
- c# - C# - Postgres:当应用程序在共享驱动器上运行时,我无法打开连接
- c++ - 为什么 Windows API 响应错误代码取决于我的日志记录语句