下面是使用一個輔助類查找最低X整數一般實現。
使用三列,將創建三個助手類實例,然後迭代數據以收集每列的3個最低值。
這段代碼的優點是:
- 只保留最低的x值
- 不需要框中整數
- 使用二進制搜索改進X值較高的性能
這意味着它應該很快並且具有較低的內存佔用量,支持無限量的數據(如果流式傳輸)。
請參閱IDEONE進行演示。
import java.util.Arrays;
class Ideone {
private static final int MIN_COUNT = 3;
public static void main(String[] args) {
int[][] data = { { 74, 85, 123 },
{ 73, 84, 122 },
{ 72, 83, 121 },
{ 70, 81, 119 },
{ 69, 80, 118 },
{ 76, 87, 125 },
{ 77, 88, 126 },
{ 78, 89, 127 } };
// Initialize min collectors
Min[] min = new Min[data[0].length];
for (int col = 0; col < min.length; col++)
min[col] = new Min(MIN_COUNT);
// Collect data
for (int row = 0; row < data.length; row++)
for (int col = 0; col < min.length; col++)
min[col].add(data[row][col]);
// Print result
for (int i = 0; i < MIN_COUNT; i++) {
for (int col = 0; col < min.length; col++)
System.out.printf("min%d = %-5d ", i + 1, min[col].get(i));
System.out.println();
}
}
}
class Min {
private int[] min;
public Min(int count) {
this.min = new int[count];
Arrays.fill(this.min, Integer.MAX_VALUE);
}
public void add(int value) {
int idx = Arrays.binarySearch(this.min, value);
if (idx != -this.min.length - 1) { // not insert at end
if (idx < 0)
idx = -idx - 1;
System.arraycopy(this.min, idx, this.min, idx + 1, this.min.length - idx - 1);
this.min[idx] = value;
}
}
public int get(int index) {
return this.min[index];
}
}
對不起,但我不知道你在問什麼。你能澄清你面臨的問題嗎? 「結果效率不高」是什麼意思? – Pshemo
您是否試圖在每列中找到三個最小的元素? –
@ PM77-1我認爲OP需要什麼,但他的數據結構和問題有點不清楚。 –