题解 | #牛的体重排序#
牛的体重排序
https://www.nowcoder.com/practice/1afd5afef2aa49a8a39b63bb9d2821f9
题目考察的知识点是:
本题主要考察知识点是分治。
题目解答方法的文字分析:
使用分治算法来排序即使用归并排序。归并排序在这里不再赘述,上网查资料即可。排序完之后根据新数组的个数长度取中间值或者中间值的平均值即可。
本题解析所用的编程语言:
java语言。
完整且正确的编程代码:
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param weightsA int整型一维数组
* @param weightsB int整型一维数组
* @return double浮点型
*/
public double findMedianSortedArrays (int[] weightsA, int[] weightsB) {
// write code here
int[] weight = new int[weightsA.length + weightsB.length];
int indexA = 0, indexB = 0, index = 0;
while (indexA < weightsA.length && indexB < weightsB.length) {
if (weightsA[indexA] < weightsB[indexB]) {
weight[index] = weightsA[indexA];
indexA++;
} else {
weight[index] = weightsB[indexB];
indexB++;
}
index++;
}
while (indexA < weightsA.length) {
weight[index] = weightsA[indexA];
indexA++;
index++;
}
while (indexB < weightsB.length) {
weight[index] = weightsB[indexB];
indexB++;
index++;
}
if (index % 2 == 0) {
return (weight[index / 2] + weight[(index / 2) - 1]) / 2.0;
} else {
return weight[index / 2];
}
}
}
#题解#
