简体   繁体   English

给定代码的时间复杂度是多少

[英]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]);
                }

            }
        }

    }

}

i think it should be n^2 but i want an explanation for the answer 我认为应该是n ^ 2,但我想为答案做一个解释

Yes you are correct its time complexity is O(n^2). 是的,您是正确的,它的时间复杂度为O(n ^ 2)。

You are doing n-1 comparisons in 1st pass, n-2 in 2nd pass, n-3 in 3rd pass and so on. 您在第一遍进行n-1个比较,在第二遍进行n-2个,在第三遍进行n-3个,依此类推。 So the total number of comparisons will be. 因此,比较的总数将是。

(n-1)+(n-2)+(n-3)+.....+3+2+1
Sum = n(n-1)/2
i.e O(n^2)

This is because big-O notation describes the nature of the algorithm. 这是因为big-O表示法描述了算法的性质。 The major term in the expansion (n-1) * (n-2) / 2 is n^2. 展开式(n-1)*(n-2)/ 2中的主要项是n ^ 2。 And so as n increases all other terms become insignificant. 因此,随着n的增加,所有其他项变得无关紧要。

是的,它是n ^ 2,因为您的两个循环都在整个限制内进行迭代,因此您有n次第一个循环进入(n-1)次第二次循环导致n ^ 2。

Just count the operations 算一下操作

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)

Total (N-1)+(N-2)+...+1 =N^2-N(N+1)/2 总(N-1)+(N-2)+ ... + 1 = N ^ 2-N(N + 1)/ 2

basically as @SSH said it's the worst case scenario, even if you have a constant case where, eg, you do that if block for even Js, the result of the algorithm would be n n/2 but for n going to infinite that "divide by 2" is irrelevant. 基本上就像@SSH所说的,这是最坏的情况,即使您有一个恒定的情况,例如,即使对Js进行阻塞,算法的结果也将是n n / 2,但是对于n来说,除以2“是无关紧要的。 For the same reason every addition to the complexity (n n/2 + 5 or n*n -5) is irrelevant as n is gonna be "pushing" to infinite 出于相同的原因,复杂度的每一个加法(n n / 2 + 5或n * n -5)都是不相关的,因为n将“推”到无穷大

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

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