[英]what is the time complexity of given code
import java.util.Scanner;
public class PairsOfElementsSumEqualsN {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
System.out.println("enter the number");
int n = s.nextInt();
int[] array = new int[]{1,2,1,2,4,5,6,7,8,9};
int j = 0;
int i = 0;
for(i = 0 ; i<array.length;i++)
{
for(j=i+1;j<array.length;j++)
{
if(array[i] + array[j] == n)
{
System.out.println(array[i] + "," + array[j]);
}
}
}
}
}
我认为应该是n ^ 2,但我想为答案做一个解释
是的,您是正确的,它的时间复杂度为O(n ^ 2)。
您在第一遍进行n-1个比较,在第二遍进行n-2个,在第三遍进行n-3个,依此类推。 因此,比较的总数将是。
(n-1)+(n-2)+(n-3)+.....+3+2+1
Sum = n(n-1)/2
i.e O(n^2)
这是因为big-O表示法描述了算法的性质。 展开式(n-1)*(n-2)/ 2中的主要项是n ^ 2。 因此,随着n的增加,所有其他项变得无关紧要。
是的,它是n ^ 2,因为您的两个循环都在整个限制内进行迭代,因此您有n次第一个循环进入(n-1)次第二次循环导致n ^ 2。
算一下操作
Outer loop 1st
Inner Loop N-1 times
print and if body are constant i.e O(1)
Outer loop 2nd
Inner Loop N-2 times
print and if body are constant i.e O(1)
...
Outer loop N-1th time
Inner Loop 1 times
print and if body are constant i.e O(1)
Outer loop N-1 time
Inner Loop 0 times
print and if body are constant i.e O(1)
总(N-1)+(N-2)+ ... + 1 = N ^ 2-N(N + 1)/ 2
基本上就像@SSH所说的,这是最坏的情况,即使您有一个恒定的情况,例如,即使对Js进行阻塞,算法的结果也将是n n / 2,但是对于n来说,除以2“是无关紧要的。 出于相同的原因,复杂度的每一个加法(n n / 2 + 5或n * n -5)都是不相关的,因为n将“推”到无穷大
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.