题解 | #售价的中位数#
售价的中位数
https://www.nowcoder.com/practice/a1c7e3a0b2fa46da8a3430617b7d74ca
题目考察的知识点
考察模拟
题目解答方法的文字分析
根据题意构建一个辅助函数用于计算中位数,每次传入对应的数组计算结果即可。
本题解析所用的编程语言
使用Java解答
完整且正确的编程代码
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param prices int整型一维数组
* @return double浮点型一维数组
*/
public double[] findMedianPrice (int[] prices) {
// write code here
List<Double> list = new ArrayList<>();
for (int i = 0; i < prices.length; i++) {
int[] sub = Arrays.copyOfRange(prices, 0, i + 1);
list.add(getMedian(sub));
}
double[] res = new double[list.size()];
for(int i=0; i<list.size(); i++){
res[i] = list.get(i);
}
return res;
}
private double getMedian(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
if (n % 2 == 1) {
return nums[n / 2];
} else {
return (nums[n / 2 - 1] + nums[n / 2]) / 2.0;
}
}
}