发现二维数组的中位数 [英] Finding median of 2D arrays

查看:470
本文介绍了发现二维数组的中位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果该参数是一个 INT [] [] 名为 ARRY ,你将如何找到它的中位数?

If the parameter was an int[][] called arry, how would you find the median of it?

很抱歉,如果我的格式是错误的,这是我第一次来这里。

Sorry if my formatting is wrong, it's my first time here.

整个二维数组计算阵列中的每个Int的中位数。

The median of the entire 2d array counting every int in the array.

所有的行具有相同的长度,例如:

All the rows are the same length, for example:

1 4 3 2 5

1 4 3 2 5

4 5 3 2 9

4 5 3 2 9

4 7 8 98 24

4 7 8 98 24

推荐答案

请删除您的问题之一,你做了两个几乎相同的问题。

Please delete one of your questions, you made two almost identical questions..

import java.util.Arrays;

public class Median {

public static void main(String[] args) {
    int[][] array2d = {
            {1, 4, 3, 2, 5},
            {4, 5, 3, 2, 9},
            {4, 7, 8, 98, 24}
    };
    // Create a new list to store the items
    int[] list = new int[array2d.length*array2d[0].length];
    // keep track of where we are.
    int listPos = 0;
    // iterate over the entire 2d array adding each integer
    for(int i = 0 ; i < array2d.length; i++) {
        for(int j = 0; j < array2d.length; j++) {
            list[listPos++] = array2d[i][j];
        }
    }
    // sort the list.
    Arrays.sort(list);
    System.out.println(median(list));
}

/**
 * Finds the median in an Array of integers.
 * @param m Array of integers
 * @return the median value
 */
public static double median(int[] m) {
    int middle = m.length/2;
    if (m.length%2 == 1) {
        return m[middle];
    } else {
        return (m[middle-1] + m[middle]) / 2.0;
    }
}

}

这篇关于发现二维数组的中位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆