转换一个二维数组为一维数组 [英] Convert a 2D array into a 1D array

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

问题描述

下面是code我到目前为止有:

Here is the code I have so far:

 public static int mode(int[][] arr) {
      ArrayList<Integer> list = new ArrayList<Integer>();
      int temp = 0;
      for(int i = 0; i < arr.length; i ++) {
          for(int s = 0; s < arr.length; s ++) {
              temp = arr[i][s];

我似乎在这一点上被卡住如何让 [I] [S] 成一个单一的维数组。当我做了打印(临时)我的二维数组中的所有元素打印出一个时间,以便但无法弄清楚如何让他们到一维数组。我是新手:(

I seem to be stuck at this point on how to get [i][s] into a single dimensional array. When I do a print(temp) all the elements of my 2D array print out one a time in order but cannot figure out how to get them into the 1D array. I am a novice :(

如何将二维数组转换成一维数组?

How to convert a 2D array into a 1D array?

目前的二维数组我一起工作是一个3×3。我试图找到二维数组中的所有整数的数学模式,如果这样的背景下是任何意义。

The current 2D array I am working with is a 3x3. I am trying to find the mathematical mode of all the integers in the 2D array if that background is of any importance.

推荐答案

您已经几乎得到了它的权利。只是一个很小的变化:

You've almost got it right. Just a tiny change:

public static int mode(int[][] arr) {
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < arr.length; i++) {
        // tiny change 1: proper dimensions
        for (int j = 0; j < arr[i].length; j++) { 
            // tiny change 2: actually store the values
            list.add(arr[i][j]); 
        }
    }

    // now you need to find a mode in the list.

    // tiny change 3, if you definitely need an array
    int[] vector = new int[list.size()];
    for (int i = 0; i < vector.length; i++) {
        vector[i] = list.get(i);
    }
}

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

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