3 回答

TA貢獻1794條經驗 獲得超7個贊
您可以將所有整數添加到 a 中List<Integer>,對其進行排序,然后獲取它的 X 最大個數:
public class foo {
public static void main(String[] args) {
int row = 3, col = 3, dep = 3;
int[][][] value = new int[row][col][dep];
value[1][2][1] = 10;
value[1][0][1] = 15;
List<Integer> listWithAll = new ArrayList<>();
/* insert the value from user or initialize the matrix*/
int max = 0;
for (row = 0; row < 3; row++)
for (col = 0; col < 3; col++)
for (dep = 0; dep < 3; dep++)
listWithAll.add(value[row][col][dep]);
listWithAll.sort(Collections.reverseOrder());
for (int i = 0; i < 10; i++) {
System.out.println(listWithAll.get(i));
}
}
}
打?。?/p>
15 10 0 0 0 0 0 0 0 0
或僅使用 Java 8 流:
List<Integer> max10 = listWithAll.stream()
.sorted(Collections.reverseOrder())
.limit(10)
.collect(Collectors.toList());
max10.forEach(System.out::println);

TA貢獻1806條經驗 獲得超5個贊
這是一種使用 來做到這一點的方法streams。我使用了完整的 2 x 2 x 2 數組以使其更容易,但它適用于任何int[][][]數組。我沒有使用嵌套循環,而是只使用flatMapped數組。
初始化數組。
int[][][] v = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
現在獲取前 4 個值(或前 N 個值)并將它們放入列表中。
int top4 = 4;
List<Integer> top4Max =
Arrays.stream(v).flatMap(Arrays::stream).flatMapToInt(
Arrays::stream).boxed().sorted(
Comparator.reverseOrder()).limit(top4).collect(
Collectors.toList());
System.out.println(top4Max);
印刷
8 7 6 5
剝離Arrays.stream一層數組。將 flatMap它們進一步扁平化為數組single dimenion。將flatMapToInt其扁平化,將stream of ints其分類并加工成有限的集合。
如果需要,您還可以將它們放入數組而不是列表中。

TA貢獻1864條經驗 獲得超6個贊
或者,可以創建一個小數組并將其與普通的 findmax 函數一起使用。
public class Array_3D {
public static void main(String[] args) {
int row = 3, col = 3, dep = 3;
int[][][] value = new int[row][col][dep];
value[1][2][1] = 10;
value[1][0][1] = 15;
int[] topten = new int[10]; //array to hold max values
int count = 0;
int candidate = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
for (int k = 0; k < dep; k++) {
if (count < 10) { //start with first ten values
topten[count] = value[i][j][k];
count++;
}
else {
candidate = value[i][j][k];
for (int x = 0; x < 10; x++) { //loop for loading top values
if (candidate > topten[x]) {
topten[x] = candidate;
break; //exit on first hit
}
}
}
}
}
}
for (int i = 0; i < 10; i++) {
System.out.print(topten[i] + " ");
}
System.out.println();
}
}
我不知道對于大型 3D 數組哪種方法更快;這里我們必須在 3D 數組中的每個點運行一個小循環,而不是創建一個全新的列表并對其進行排序。顯然,這在內存使用方面獲勝,但不確定速度。[編輯注意,這將按原樣返回前十個值的未排序數組]。
添加回答
舉報