题解 | #牛的体重排序#

牛的体重排序

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];
        }
    }
}

#题解#
全部评论
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 fal = weightsA.length; int sal = weightsB.length; int[] result = new int[fal + sal ]; System.arraycopy(weightsA, 0, result, 0, fal); System.arraycopy(weightsB, 0, result, fal, sal); 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]; } } }
点赞 回复 分享
发布于 2023-07-28 11:46 湖南

相关推荐

02-05 08:18
四川大学 Java
在思考的熊熊很讨厌吃香菜:不是,我门头沟学院呢?这都没排上?
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务