我在学习数据结构时刚刚写了一个关于数组旋转的代码。我需要知道如何通过测量时间和空间复杂度来改进下面的程序。阵列旋转程序。将数组旋转 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] + " "); } }
2 回答
慕田峪9158850
TA贡献1794条经验 获得超7个赞
时间复杂度:O(n),其中 n = 数组长度(因为没有嵌套的 for 循环)
空间复杂度:O(2) 即 O(1)(因为这个数组的大小 firstOccurenceArray 是常数,即 2)
- 2 回答
- 0 关注
- 183 浏览
添加回答
举报
0/150
提交
取消