我得到了长度从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 percent3(int [] a){}
这是CS课程的一项作业,旨在帮助学生练习递归。我感到困惑,因为我不确定如果要使用递归应该从哪里开始。 我可以进行从类中学到的简单递归,例如fibbonacci序列或阶乘数。但是这个问题,我似乎找不到与应用于较简单的递归问题相同的模式...
如果您能将我引向某个方向并给我您的任何提示,我将不胜感激。 谢谢。
答案 0 :(得分:2)
您可能打算处理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
。