Java 需要进一步优化代码
以下是我需要优化的代码:Java 需要进一步优化代码,java,Java,以下是我需要优化的代码: Scanner sc = new Scanner(System.in); int sum=0; //stores the result 创建4个列表,A B C分别保存输入值,D获得最终结果列表,S存储总和 ArrayList<Integer> listA = new ArrayList<Integer>(); ArrayList<Integer> listB = new Arra
Scanner sc = new Scanner(System.in);
int sum=0; //stores the result
创建4个列表,A B C分别保存输入值,D获得最终结果列表,S存储总和
ArrayList<Integer> listA = new ArrayList<Integer>();
ArrayList<Integer> listB = new ArrayList<Integer>();
ArrayList<Integer> listC = new ArrayList<Integer>();
ArrayList<Integer> listD = new ArrayList<Integer>();
ArrayList<Integer> listS = new ArrayList<Integer>();
每个测试用例的第一行包含3个整数:p、q和r。它们分别表示A、B和C的长度。
第二行包含p个整数,它们是A的元素。第三行包含q个整数,它们是B的元素。第四行包含r个整数,它们是C的元素
for(int i=0; i<T; i++){
int p = sc.nextInt();
int q = sc.nextInt();
int r = sc.nextInt();
for(int j=0; j<p; j++){
int x = sc.nextInt();
listA.add(x);
}
for(int j=0; j<q; j++){
int x = sc.nextInt();
listB.add(x);
}
for(int j=0; j<r; j++){
int x = sc.nextInt();
listC.add(x);
}
for (int k = 0; k < listA.size(); k++){
int a = listA.get(k);
for(int j=0; j<listB.size(); j++){
int b = listB.get(j);
for(int l=0; l<listC.size(); l++){
int c=listC.get(l);
//System.out.println("a: "+a+" b: "+b+" c: "+c);
int d = (a+b)*(b+c);
listD.add(d);
}
}
}
for(int y=0; y<listD.size(); y++){
sum += listD.get(y);
}
sum = sum%1000000007;
System.out.println(listD);
listS.add(sum);
}
String formattedString = listS.toString()
.replace(",", "\n") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "") //remove the left bracket
.replace(" ", "")
.trim();
System.out.println(formattedString);
sc.close();
对于(int i=0;i所以基本上你需要计算上述代码中的sum
的值,它基本上是(a+b)*(b+c)
的所有可能排列的总和。我将其公式化为一个简单的西格玛方程,并将其简化如下:
从上一个等式中,如果你考虑每个列表的总和分别是x,y和z,则上述方程归结为:
sum=rXY+qXZ+pr*(sum of squares of each element in listB)+p*YZ
与代码中的O(pqr)
相比,在最坏的情况下,这是O(q^2)
的顺序。这非常有效!但是如果在执行(a+b)*(b+c)之前在所有可能的排列中,我还想检查a=c?基本上是基于你想乘的条件的结果吗?是的!你得到了。这使它变得非常简单。只需对所有列表排序。迭代a
,直到你找到一个小于b
的值。当你迭代c
时,找到哦,是的。应该行了!我现在就试试。谢谢!
sum=rXY+qXZ+pr*(sum of squares of each element in listB)+p*YZ