简体   繁体   中英

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

or does work like nested loops

and what if we break or made continue in the second loop what would happen? 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.

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. 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.

The time complexity is O(n * m) as a consequence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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