我在學(xué)習(xí)數(shù)據(jù)結(jié)構(gòu)時(shí)剛剛寫了一個(gè)關(guān)于數(shù)組旋轉(zhuǎn)的代碼。我需要知道如何通過測量時(shí)間和空間復(fù)雜度來改進(jìn)下面的程序。陣列旋轉(zhuǎn)程序。將數(shù)組旋轉(zhuǎn) 2 將使數(shù)組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貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超7個(gè)贊
時(shí)間復(fù)雜度:O(n),其中 n = 數(shù)組長度(因?yàn)闆]有嵌套的 for 循環(huán))
空間復(fù)雜度:O(2) 即 O(1)(因?yàn)檫@個(gè)數(shù)組的大小 firstOccurenceArray 是常數(shù),即 2)
- 2 回答
- 0 關(guān)注
- 200 瀏覽
添加回答
舉報(bào)
0/150
提交
取消