What is the time complexity of this code? I have a 2d array and every time theres a 0 i want to change the value of the entire row and column to zero.
for(int i=0; i < copy.length; i++){
for(int j=0; j < copy[0].length; j++){
if(copy[i][j] == 0){
for(int z =0; z < copy.length; z++){
a[z][j] = 0;
}
for(int z = 0; z < copy[0].length; z++){
a[i][z] = 0;
}
}
}
}
Worst case => all zeros.
For copy[m][n];
for(int i=0; i < copy.length; i++){ ===> m times
for(int j=0; j < copy[0].length; j++){ ===> n times
if(copy[i][j] == 0){
for(int z =0; z < copy.length; z++){ ===> m times
a[z][j] = 0;
}
for(int z = 0; z < copy[0].length; z++){ ===> n times
a[i][z] = 0;
}
}
}
}
Time-complexity = m*n*(m+n) = mn(m+n)
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.