我有以下代碼,而不是使用掃描儀功能鍵入數字。我想改用數組。我該怎么做呢?我需要幫助。提前致謝public class salomon { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; int[] minHeap = new int[n]; int[] maxHeap = new int[n]; int minHeapSize = 0; int maxHeapSize = 0; float currentMedian = 0; for (int a_i = 0; a_i < n; a_i++) { a[a_i] = in.nextInt(); if (a[a_i] < currentMedian) { maxHeap[maxHeapSize++] = a[a_i]; // making sure the max heap has maximum value at the top if (maxHeap[maxHeapSize - 1] > maxHeap[0]) { swap(maxHeap, maxHeapSize - 1, 0); } } else { minHeap[minHeapSize++] = a[a_i]; // making sure the min heap has minimum value at the top if (minHeap[minHeapSize - 1] < minHeap[0]) { swap(minHeap, minHeapSize - 1, 0); } } // if the difference is more than one if (Math.abs(maxHeapSize - minHeapSize) > 1) { if (maxHeapSize > minHeapSize) { swap(maxHeap, maxHeapSize - 1, 0); minHeap[minHeapSize++] = maxHeap[--maxHeapSize]; swap(minHeap, 0, minHeapSize - 1); buildMaxHeap(maxHeap, maxHeapSize); } else { swap(minHeap, minHeapSize - 1, 0); maxHeap[maxHeapSize++] = minHeap[--minHeapSize]; swap(maxHeap, 0, maxHeapSize - 1); buildMinHeap(minHeap, minHeapSize); } }當我輸入 6、12、4、5、3、8、7 并輸入時 - 我得到移動中位數12.08.05.04.55.06.0我想用數組 {6, 12, 4, 5, 3, 8, 7}` 代替掃描儀,以及如何調整代碼。謝謝
1 回答

三國紛爭
TA貢獻1804條經驗 獲得超7個贊
第一個值6是數組長度。假設您打算保留它,您將刪除“不是大象”的所有內容(即所有中位數計算),并重命名int[] a為int[] f. 喜歡,
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] f = new int[n];
for (int i = 0; i < n; i++) {
f[i] = in.nextInt();
}
System.out.println(Arrays.toString(f));
}
當使用您的示例輸入執行時,此輸出
[12, 4, 5, 3, 8, 7]
如果你真的也想要這六個,那么你需要添加它。喜歡,
int[] f = new int[n + 1];
f[0] = n;
for (int i = 1; i <= n; i++) {
f[i] = in.nextInt();
}
System.out.println(Arrays.toString(f));
哪些輸出(根據要求)
[6, 12, 4, 5, 3, 8, 7]
添加回答
舉報
0/150
提交
取消