时间复杂性分析:更好的解释?

时间:2016-07-06 05:20:29

标签: algorithm time-complexity

我遇到以下代码,找到满足Triangle sum属性的三元组。

// Function to count all possible triangles with arr[]
    // elements
    static int findNumberOfTriangles(int arr[])
    {
        int n = arr.length;
        // Sort the array elements in non-decreasing order
        Arrays.sort(arr);

        // Initialize count of triangles
        int count = 0;

        // Fix the first element.  We need to run till n-3 as
        // the other two elements are selected from arr[i+1...n-1]
        for (int i = 0; i < n-2; ++i)
        {
            // Initialize index of the rightmost third element
            int k = i + 2;

            // Fix the second element
            for (int j = i+1; j < n; ++j)
            {
                /* Find the rightmost element which is smaller
                   than the sum of two fixed elements
                   The important thing to note here is, we use
                   the previous value of k. If value of arr[i] +
                   arr[j-1] was greater than arr[k], then arr[i] +
                   arr[j] must be greater than k, because the
                   array is sorted. */
                while (k < n && arr[i] + arr[j] > arr[k])
                    ++k;

               /* Total number of possible triangles that can be
                  formed with the two fixed elements is k - j - 1.
                  The two fixed elements are arr[i] and arr[j].  All
                  elements between arr[j+1] to arr[k-1] can form a
                  triangle with arr[i] and arr[j]. One is subtracted
                  from k because k is incremented one extra in above
                  while loop. k will always be greater than j. If j
                  becomes equal to k, then above loop will increment
                  k, because arr[k] + arr[i] is always/ greater than
                  arr[k] */
                count += k - j - 1;
            }
        }
        return count;
    }

有人可以更好地解释为什么这个解决方案的时间复杂度是O(n ^ 2)而不是O(n ^ 3)?我的理解是,对于每个i和j,k也会变化。

2 个答案:

答案 0 :(得分:2)

上述解决方案的时间复杂度为O(n^2),因为您可以看到k的值在第二个for循环之前初始化。在第二个for 循环k的值在while条件下增加。 while条件终止后,loop将运行下一个j值并且 k的值与之前在while循环中终止的值保持一致。 一旦k的值等于n,那么在此之后它将不会针对j的任何值运行。

因此第二个for循环仅从k=i+2运行到n。因此,复杂性为O(n^2)

答案 1 :(得分:1)

唯一可以执行超过O(n ^ 2)次的语句是最嵌套的++k语句。

k永远不会超过n,并会重置(到非负数)n-2次。这证明++k语句最多执行n(n-2) = O(n^2)次。