我得到了從 1 個元素到 100_000 個元素的不同長度的 int 數組。我需要找到給定 int 數組的近似中值。例如, given array of [4], median is 4 since there is only 1 element given array of [4,5], (4+5) / 2.0 = 4.5 is median. given array of [4,5,6], break array into 3 pieces [4][5][6] what is the middle value ? 5 = median. given array of [4,5,6,7], break array into 3 pieces [4][5,6][7] median of [4] is 4 median of [5,6] is 5.5 median of [7] is 7 4 vs 5.5 vs 7 median of given array [4,5,6,7] is 5.5使用給定的數組,我應該將數組分成三部分(不創建新數組或修改給定數組)。將給定數組分成三部分,這是三種可能性 1. given array's length(6) % 3 = 0 (The case when a remainder is 0) given array --> [2,3,5,3,1,4] divide into 3 --> [2,3][5,3][1,4] each pieces are length of n/3. In this particular case(n = 6), 6/3 = 2 = length of each piece. 2. given array's length(10) % 3 = 1 (The case when a remainder is 1) given array --> [1,2,-20,-10,7,20,-3,100,6,92] divide into 3 --> [1,2,-20][-10,7,20,-3][100,6,92] left and right side piece is length of n/3(10/3). middle piece is n/3(10/3) rounded up 3. given array's length(8) % 3 = 2 (Last case when a remainder is 2) given array --> [1,2,10,7,20,-3,100,6] divide into 3 --> [1,2,10][7,20][-3,100,6]實現方法 public static double median3(int[] a) {}這是cs課程的作業,旨在幫助學生練習遞歸。我感到困惑,因為如果我要使用遞歸,我不太確定應該從哪里開始。我可以進行從課堂上學到的簡單遞歸,例如斐波那契數列或階乘數。但是這個問題,我似乎找不到我應用于更簡單的遞歸問題的相同模式......如果你能給我一些指導并給我一些建議,我將不勝感激。謝謝你。
1 回答

MYYA
TA貢獻1868條經驗 獲得超4個贊
您可能要處理 3 種情況:
對于長度 = 1,您將元素作為該子數組的中位數
對于長度 = 2,您將中位數計算為這兩個元素的平均值
對于長度 >= 3,您根據上述規則拆分數組,然后將相同的方法(即這 3 種情況)應用于第二個(中心)數組。您不需要拆分數組,只需跟蹤標記第二個和第三個子數組的第一個元素的索引。
例子:
讓我們從數組開始[1,2,-20,-10,7,20,-3,100,6,92]
。它的長度 >= 3 所以你把它分成[1,2,-20][-10,7,20,-3][100,6,92]
,
現在您遞歸地處理中心數組[-10,7,20,-3]
。它的長度仍然 >3,所以你再次分裂并得到[-10[[7,20][-3]
.
“新”中心數組是[7,20]
,因為長度為 2,所以您將中位數計算為(7+20)/2.0 = 13.5
。
添加回答
舉報
0/150
提交
取消