【问题标题】:How can I determine Time and Space Complexity of the below program?如何确定以下程序的时间和空间复杂度?
【发布时间】:2018-06-20 10:36:42
【问题描述】:

我刚刚在学习数据结构时写了一个关于数组旋转的代码。我需要知道如何通过测量时间和空间复杂度来改进下面的程序。

数组旋转程序。 将数组旋转 2 将形成数组

1,2,3,4 输入

3,4,1,2 输出

  public class Program
    {

        public static void Main(string[] args)
        {
            int arrayCount = 0;
            int rotate = 2;
        int []answer = new int[4];

            for (int i = 0; i < answer.Length; i++)
            {
                answer[i] = Convert.ToInt32(Console.ReadLine());
            }
            arrayCount = answer.Count();
            ArrayRotation.displayRotatedArray(answer, rotate, arrayCount);
            ArrayRotation.printArray(answer, arrayCount);
            Console.ReadKey();
        }
    }

 public static class ArrayRotation
    {
        public static void displayRotatedArray(int []temp, int rotate, int count)
        {

           int c = rotate;
            int d = rotate;
            int[] firstOccurenceArray = new int[rotate];

                for (int g = 0; g < rotate; g++)
                {
                    int num = g;
                    firstOccurenceArray[g] = temp[g];
                }
                for (int i = 0; i < temp.Length - c; i++)
                {
                    temp[i] = temp[rotate];
                    rotate++;
                }
            for (int k = 1; k < d + 1; k++)
            {
                temp[count - k] = firstOccurenceArray[c - 1];
                c--;
            }
        }
        /* utility function to print an array */
       public static void printArray(int[] temp, int size)
        {
            for (int i = 0; i < size; i++)
                Console.Write( temp[i] + " ");
        }
    }

【问题讨论】:

    标签: c# arrays data-structures


    【解决方案1】:

    计算时间复杂度:操作数随着输入参数大小的变化而变化。

    对于这个示例操作正在改变,如前所述:

    (2) + 2*rotate + 2* temp.Length + 2 * rotate

    最大值可以是 2 + (6 * temp.Length) 所以时间复杂度是O(n)。

    空间复杂度:O(rotate),最大到 O(n)

    您可以通过就地交换(杂耍算法)数组值来优化 O(n) 时间复杂度和 O(1) 空间复杂度的问题。

    参考: https://www.geeksforgeeks.org/array-rotation

    【讨论】:

      【解决方案2】:

      时间复杂度:O(n),其中 n = 数组长度(因为没有嵌套的 for 循环)

      空间复杂度:O(2),即 O(1)(因为这个数组 firstOccurenceArray 的大小是恒定的,即 2)

      【讨论】:

      • 感谢您的回答,但是如果我将常量值更改为大于 2 会发生什么?
      • 然后,根据您的代码,在所有情况下,if(rotate>arrayCount) TimeComplexity = O(rotate) else TimeComplexity=O(arrayCount) And SpaceComplexity = O(rotate)。
      • 如果你这样做,你可以提高你代码的时间复杂度和空间复杂度rotate=rotate%arrayCount
      猜你喜欢
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-14
      • 2016-05-15
      • 1970-01-01
      相关资源
      最近更新 更多