我在學習數據結構時剛剛寫了一個關于數組旋轉的代碼。我需要知道如何通過測量時間和空間復雜度來改進下面的程序。陣列旋轉程序。將數組旋轉 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條經驗 獲得超8個贊
時間復雜度:O(n),其中 n = 數組長度(因為沒有嵌套的 for 循環)
空間復雜度:O(2) 即 O(1)(因為這個數組的大小 firstOccurenceArray 是常數,即 2)
- 2 回答
- 0 關注
- 219 瀏覽
添加回答
舉報
0/150
提交
取消
