【发布时间】:2020-09-25 17:39:24
【问题描述】:
我正在尝试按降序打印由 ArrayL1.get(i)、ArrayL2.get(j) 之和形成的最大数字(数组大小)。不知何故,我下面的代码不起作用。我需要分别获得 O(n^2 log n) 和 O(n) 的时间和空间复杂度。
例如:
输入
3
1 2 3
4 5 6
输出
9
8
8
import java.io.*;
import java.util.*;
public class Source {
public static void main(String args[]) {
//below two ArrayList are used to store the given input
ArrayList<Integer> ArrayL1 = new ArrayList<Integer>();
ArrayList<Integer> ArrayL2 = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
int n, i;
// size of ArrayL1 = size of ArrayL2 = n
n = in.nextInt();
for (i = 0; i < n; i++) {
ArrayL1.add(in.nextInt());
}
for (i = 0; i < n; i++) {
ArrayL2.add(in.nextInt());
}
KMaxCombinations(ArrayL1,ArrayL2);
}
static void KMaxCombinations(ArrayList<Integer> ArrayL1,ArrayList<Integer> ArrayL2) {
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Collections.reverseOrder());
int N = ArrayL1.size();
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
pq.add(ArrayL1[i] + ArrayL2[j]);
int count = 0;
while (count < N)
{
System.out.println(pq.peek());
pq.remove();
count++;
}
}
}
【问题讨论】:
标签: java arraylist data-structures heap