问题描述
我试图打印由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++;
}
}
}
解决方法
在您的代码中,您尝试使用不正确的语法从ArrayList访问元素。表示您正在使用以下语法
ArrayL1.[i] + ArrayL2.[j]
理想情况下应该是
ArrayL1.get(i) + ArrayL2.get(j)
我已经更新了Source.java
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.get(i) + ArrayL2.get(j));
int count = 0;
while (count < N) {
System.out.println(pq.peek());
pq.remove();
count++;
}
}
}
更改上述语法后,程序会给出
输出:
3
1 2 3
4 5 6
9
8
8
您还有其他期望吗?