简体   繁体   English

棘手的嵌套循环 O(n+m)?

[英]Tricky nested loop O(n+m)?

I did not quite understand how does this loop works:我不太明白这个循环是如何工作的:

 for(int i = 0, j = 0; i < n; i++){
        for(; j < m; j++){

more Appropriate exemple更合适的例子

int arr[] = {1, 2, 3, 4, 5, 6, 7};
int arr1[] = {7, 6, 5, 4, 3, 2, 1};
for (int i = 0, j = 0; i < n; i++) {
  for (; j < m; j++) {
    if (arr[i] + arr1[j] < 0) break;
    if (arr[i] + arr1[j] > max) max = arr[i] + arr1[j];
  }
}

when the loop starts do they work simultaneously?like thi like [[1+7][2+6][3+5] etc.....], means as it increment they both make sum当循环开始时,它们是否同时工作?就像 [[1+7][2+6][3+5] 等.....],意味着随着它的增加,它们都会产生总和

or does work like nested loops或者像嵌套循环一样工作

and what if we break or made continue in the second loop what would happen?如果我们在第二个循环中 break 或 make continue 会发生什么? well detailed and more informations and explanation would be appreciated非常详细和更多的信息和解释将不胜感激

Complexity will be O(n+m) as the inner loop will run only once and j is not being reset to 0.复杂度将是 O(n+m),因为内部循环只会运行一次并且 j 不会被重置为 0。

It is a nested loop with an inner and an outer loop.它是一个内循环和外循环的嵌套循环。 The variable for the inner loop is initialized in the outer loop.内循环的变量在外循环中初始化。 It is pretty uncommon.这很不常见。 If you are unsure how it behaves, then you could just print something to System.out here and there.如果您不确定它的行为方式,那么您可以在这里和那里打印一些内容到System.out It increments (i = 0, j = 0), (i = 0, j = 1), ..., (i = 0, j = m), (i = 1, j = 0),... If you break or continue in the inner loop then it continues with (i+1, j) since j is not reset to 0.它递增 (i = 0, j = 0), (i = 0, j = 1), ..., (i = 0, j = m), (i = 1, j = 0),... 如果您在内部循环中中断或继续,然后它以 (i+1, j) 继续,因为 j 未重置为 0。

The time complexity is O(n * m) as a consequence.结果,时间复杂度为 O(n * m)。

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

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