题解 | #三个牛群中位数#
三个牛群中位数
https://www.nowcoder.com/practice/8bc0369faf7c4ac5ab336f38e859db05
考察数组排序以及合并。数组copy后直接调用了API进行排序应该是最快的。
完整Java代码如下所示
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param herd1 int整型一维数组 * @param herd2 int整型一维数组 * @param herd3 int整型一维数组 * @return double浮点型 */ public double findMedianSortedArray (int[] herd1, int[] herd2, int[] herd3) { // write code here int fal = herd1.length; int sal = herd2.length; int mal = herd3.length; int[] result = new int[fal + sal + mal]; System.arraycopy(herd1, 0, result, 0, fal); System.arraycopy(herd2, 0, result, fal, sal); System.arraycopy(herd3, 0, result, fal + sal, mal); Arrays.sort(result); int n = result.length; if (n % 2 == 0) { return (result[n / 2] + result[n / 2 - 1]) / 2.0; } else { return result[n / 2]; } } }