首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何确定以下程序的时间和空间复杂性?

如何确定以下程序的时间和空间复杂性?
EN

Stack Overflow用户
提问于 2018-06-20 10:36:42
回答 2查看 1.2K关注 0票数 1

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

数组旋转程序。将数组旋转为2将使数组

1,2,3,4投入

3,4,1,2产出

代码语言:javascript
运行
复制
  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] + " ");
        }
    }
EN

Stack Overflow用户

发布于 2018-06-20 10:51:30

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

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

票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50946198

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档