algorithm - 使用 mod 操作时如何计算时间复杂度
问题描述
我正在尝试查找以下代码的时间复杂度。
N= number of elements in array
D= a constant: D>1
V= a constant: V>1000
counter=1; //the maximum value of the counter is N/D.
for(i=0; i<N; i++)
{
[OP1] O1_Operation; // O(1) operation. [Total: N times]
[OP2] if(i%D!=0) continue; // O(1) operation. [Total: N times]
[OP3] for(j=0;j<counter;j++) // [Total: {(N/D)*((N/D)+1)}/2 times]
[OP4] for(s=0;s<V;s++)
[OP5] O1_Operation; // O(1) operation. [Total: (V*{(N/D)*((N/D)+1)}/2) times]
[OP6] counter++; // O(1) operation. [Total: N/D times]
}
我添加了每个操作的时间复杂度和它将被执行的总时间。这段代码让我感到困惑是因为 mod 操作。此 mod 将仅允许 (N/D) 操作来完成代码 OP[3-6]。
对于 [OP3],第一次执行 1 次,第二次执行 2 次,...,N/D 次。因此,执行的总数可以是 [(N/D) * ( (N/D)+1)] /2。删除 D 和 V 因为它们是常量将导致整个代码的复杂度为 O(N^2)。
这个对吗?
解决方案
这取决于 V 和 D 的性质,但您的整体时间复杂度分析是正确的,您的结论可能是 O(VN^2/D^2) 或 O(N^2),具体取决于您如何看待 V 和D 和问题/问题的性质。
推荐阅读
- python - 最大连续字数
- python - 从具有多列的 Pandas 数据框中创建一维 Numpy“类数组”对象
- system.reactive - Rx.Net 忽略某些异常但处理其余异常
- javascript - 在json响应中获得未定义的第一个答案
- javascript - 有没有办法获得同名的外部范围变量?
- wso2 - WSO2 ESB:如何处理端点返回的内部错误
- arrays - 使用 List 解析侧 JSON 数组中的 JSON 数组
扑 - wordpress - wordpress 上的前端邮件客户端?可能吗?
- php - 图书馆管理系统 - 如何将泰米尔语和英语书籍的详细信息存储在 phpmyadmin 的同一张表中?
- javascript - 如何使用 JavaScript 和 Node.Js 在 Fusion Chart 上传递 MySQL 数据?