将二维数组转换为一维数组

新手上路,请多包涵

这是我到目前为止的代码:

  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) 时,我的二维数组的所有元素一次按顺序打印一个,但无法弄清楚如何将它们放入一维数组中。我是新手:(

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

我目前使用的二维数组是 3x3。如果该背景很重要,我试图找到二维数组中所有整数的数学模式。

原文由 Kristopher 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

你几乎做对了。只是一个微小的变化:

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

原文由 alf 发布,翻译遵循 CC BY-SA 3.0 许可协议

在 Java 8 中,您可以使用对象流将矩阵映射到向量。

将任意类型和任意长度的对象矩阵转换为向量(数组)

 String[][] matrix = {
    {"a", "b", "c"},
    {"d", "e"},
    {"f"},
    {"g", "h", "i", "j"}
};

String[] array = Stream.of(matrix)
                       .flatMap(Stream::of)
                       .toArray(String[]::new);

如果您正在寻找特定于 int 的方式,我会选择:

 int[][] matrix = {
    {1, 5, 2, 3, 4},
    {2, 4, 5, 2},
    {1, 2, 3, 4, 5, 6},
    {}
};

int[] array = Stream.of(matrix) //we start with a stream of objects Stream<int[]>
                    .flatMapToInt(IntStream::of) //we I'll map each int[] to IntStream
                    .toArray(); //we're now IntStream, just collect the ints to array.

原文由 t4dohx 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题