具有嵌套 if-else 的循环的时间复杂度
Time complexity of a loop with a nested if-else
// Every iteration of loop counts triplet with
// first element as arr[i].
for (int i = 0; i < n - 2; i++) {
// Initialize other two elements as corner
// elements of subarray arr[j+1..k]
int j = i + 1, k = n - 1;
// Use Meet in the Middle concept
while (j < k) {
// If sum of current triplet is more or equal,
// move right corner to look for smaller values
if (arr[i] + arr[j] + arr[k] >= sum)
k--;
// Else move left corner
else {
// This is important. For current i and j,
// there are total k-j third elements.
for (int x = j + 1; x <= k; x++)
cout << arr[i] << ", " << arr[j]
<< ", " << arr[x] << endl;
j++;
}
}
}
该算法的时间复杂度是多少?是O(n*n(吗? 这是来自geekforgeeeks网页的问题。你如何处理 else 语句中的循环?
将代码分解为多个部分并找到每个部分的运行时。
外部 for 循环是 O(n(。
每次调用该循环时,您都会调用一个 while 循环。因此,您将乘以两个循环的复杂性。
要弄清楚 while 循环的运行时间,您必须查看 if 和 else 块。如果 if 块每次都运行,那么 while 循环将具有 O(n( 复杂性。如果 else 部分每次都运行,那么 while 循环将具有 O(n^2( 复杂性。
如果我们考虑最坏的情况,那么您将忽略 if 块运行时。因此,while 循环运行时为 O(n^2(,并且通过外部 for 循环调用了 n 次。
因此,这一切的运行时间应该是 O(n^3(。
相关文章:
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- while循环中while循环的时间复杂度是多少
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 函数的时间复杂度是多少?
- 如何检查两个 std::向量在小于 O(n) 的时间复杂度内是否相等
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 如何计算此排序函数的时间复杂度?
- 计算两个代码块的时间复杂度
- C++ 中具有 O(1) 搜索时间复杂度的数据结构
- 具有嵌套 if-else 的循环的时间复杂度
- 将树节点添加到向量向量中的 n 元树遍历的平均和最坏情况时间复杂度是多少?
- 如何计算函数的时间复杂度?
- 求解包含"variables"的 T(n) 时间复杂度
- 2 个嵌套循环的时间复杂度
- 如何在 c++ 下使用嵌套循环和正则表达式降低时间复杂度?
- 带有 if 语句的嵌套循环的时间复杂度
- C++ 数组循环的时间复杂度
- 以下循环的时间复杂度是多少
- 内部 for 循环的时间复杂度
- 嵌套循环的时间复杂度:cn(n+1)/2从何而来