这是我到目前为止的代码:
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];
Run Code Online (Sandbox Code Playgroud)
关于如何[i][s]进入单维数组,我似乎陷入了困境.当我做一个print(temp)2D阵列的所有元素按顺序打印一次但无法弄清楚如何将它们放入1D阵列.我是新手:(
如何将2D数组转换为1D数组?
我正在使用的当前2D阵列是3x3.我试图找到2D阵列中所有整数的数学模式,如果该背景具有任何重要性.
你几乎做对了.只是一个微小的变化:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在 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);
Run Code Online (Sandbox Code Playgroud)
如果您正在寻找特定于 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.
Run Code Online (Sandbox Code Playgroud)
我不确定您是否正在尝试将 2D 数组转换为 1D 数组(如您的问题所述),或者将 2D 数组中的值放入您拥有的 ArrayList 中。我将假设第一个,但我会很快说您需要为后者做的就是 call list.add(temp),尽管temp在您当前的代码中实际上不需要。
如果您尝试使用一维数组,那么以下代码就足够了:
public static int mode(int[][] arr)
{
int[] oneDArray = new int[arr.length * arr.length];
for(int i = 0; i < arr.length; i ++)
{
for(int s = 0; s < arr.length; s ++)
{
oneDArray[(i * arr.length) + s] = arr[i][s];
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38728 次 |
| 最近记录: |