我有以下代码,而不是使用扫描仪功能键入数字。我想改用数组。我该怎么做呢?我需要帮助。提前致谢
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.0
8.0
5.0
4.5
5.0
6.0
我想用数组 {6, 12, 4, 5, 3, 8, 7}` 代替扫描仪,以及如何调整代码。谢谢
三国纷争
相关分类