题解 | #三个牛群中位数# java

三个牛群中位数

https://www.nowcoder.com/practice/8bc0369faf7c4ac5ab336f38e859db05

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 n1 = herd1.length;
        int n2 = herd2.length;
        int n3 = herd3.length;
        int[] nums1 = new int[n1 + n2 + n3];
        for (int i = 0; i < n1; i++) {
            nums1[i] = herd1[i];
        }
        for (int i = 0; i < n2; i++) {
            nums1[n1 + i] = herd2[i];
        }
        for (int i = 0; i < n3; i++) {
            nums1[n1 + n2 + i] = herd3[i];
        }
        Arrays.sort(nums1);
        int n = nums1.length;
        if (n % 2 == 0) {
            return (nums1[n / 2] + nums1[n / 2 - 1]) / 2.0;
        } else {
            return nums1[n / 2];
        }
    }
}

使用的是Java语言。

该题考察的知识点是数组的合并、排序和求中位数。

代码的文字解释如下:

  1. 使用循环将三个输入数组中的元素逐个复制到nums1数组中,并保持原始顺序。首先,第一个循环将herd1数组的元素复制到nums1数组前n1个位置;然后,第二个循环将herd2数组的元素复制到nums1数组从第n1个位置开始的n2个位置;最后,第三个循环将herd3数组的元素复制到nums1数组从第n1+n2个位置开始的n3个位置。
  2. 使用Arrays.sort()函数对nums1数组进行排序,以获得升序排列的数组。
  3. 判断排序后数组nums1的长度。如果长度为偶数,则返回中间两个数字的平均值;如果长度为奇数,则返回中间数字作为中位数。
  4. 返回中位数作为结果。
全部评论

相关推荐

牛客41406533...:回答他在课上学,一辈子待在学校的老教授用三十年前的祖传PPT一字一句的讲解,使用谭浩强红皮书作为教材在devc++里面敲出a+++++a的瞬间爆出114514个编译错误来学这样才显得专业
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务