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

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

问题描述

这是我目前的代码:

 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] 放入一维数组中.当我执行 print(temp) 时,我的 2D 数组的所有元素都会按顺序打印一次,但无法弄清楚如何将它们放入一维数组中.我是新手:(

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?

我当前使用的 2D 阵列是 3x3.如果背景有任何重要性,我试图找到二维数组中所有整数的数学模式.

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天全站免登陆