我有以下代码,而不是使用扫描仪功能键入数字。我想改用数组。我该怎么做呢?我需要帮助。提前致谢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
提交
取消