面试题答案
一键面试- 实现步骤:
- 首先,使用
reduce
函数遍历Map
返回的数组。 - 对于每个对象,计算其
value
数组的中位数和标准差。 - 中位数计算:如果数组长度为奇数,中位数是排序后数组中间的元素;如果长度为偶数,中位数是排序后中间两个元素的平均值。
- 标准差计算:先计算平均值,然后计算每个值与平均值的差的平方和,再除以数组长度,最后取平方根。
- 将每个组的中位数和标准差结果存储在新的数组中。
- 首先,使用
- 代码如下:
const mapResult = [{ key: 'group1', value: [1, 2, 3] }, { key: 'group2', value: [4, 5] }];
const result = mapResult.reduce((acc, current) => {
const sortedValues = current.value.slice().sort((a, b) => a - b);
const length = sortedValues.length;
const median = length % 2 === 0?
(sortedValues[length / 2 - 1] + sortedValues[length / 2]) / 2 :
sortedValues[Math.floor(length / 2)];
const mean = sortedValues.reduce((sum, value) => sum + value, 0) / length;
const variance = sortedValues.reduce((sum, value) => sum + Math.pow(value - mean, 2), 0) / length;
const standardDeviation = Math.sqrt(variance);
acc.push({
key: current.key,
median,
standardDeviation
});
return acc;
}, []);
console.log(result);
上述代码以JavaScript为例,实现了对给定Map
结果格式中每个组内值的中位数和标准差的计算。如果是其他语言,实现思路类似,但具体语法会有所不同。例如在Python中:
import math
map_result = [{"key": "group1", "value": [1, 2, 3]}, {"key": "group2", "value": [4, 5]}]
result = []
for item in map_result:
sorted_values = sorted(item["value"])
length = len(sorted_values)
median = (sorted_values[length // 2 - 1] + sorted_values[length // 2]) / 2 if length % 2 == 0 else sorted_values[length // 2]
mean = sum(sorted_values) / length
variance = sum((x - mean) ** 2 for x in sorted_values) / length
standard_deviation = math.sqrt(variance)
result.append({
"key": item["key"],
"median": median,
"standard_deviation": standard_deviation
})
print(result)