【发布时间】:2020-08-13 22:49:55
【问题描述】:
给定两个数组列表 A 和 B,A={3,4,5] 和 B=[4,7],计算 A 中有多少个数小于或等于 B 中的每个元素。在这种情况下 B.get (0)=4 在 A 中具有小于或等于 2 个值,即 3 和 4,类似地 7 具有 3 个值。所以函数应该返回 list=[2,3]。 我已经使用两个 for 循环解决了这个问题,这适用于较小的输入,但是随着大小的增长,性能会下降。
import java.util.*;
public class checkDiff{
public static void check(List<Integer> A, List<Integer> B) {
List<Integer> result=new ArrayList<Integer>();
for(int i=0;i<B.size();i++){
int count=0;
for(int j=0;j<A.size();j++){
if(A.get(j)<=B.get(i)){
count++;
}
}
result.add(i,count);
}
for(int x:result){
System.out.println(x);
}
}
public static void main(String []args){
List<Integer> A=new ArrayList<Integer>();
List<Integer> B=new ArrayList<Integer>();
A.add(3);
A.add(4);
A.add(7);
B.add(4);
B.add(7);
check(A,B);
}
}
有什么办法可以优化这段代码吗?请帮忙
【问题讨论】:
-
如果您要对每个数组进行排序,您可以并行遍历这两个数组,因为您会知道
B.get(0)是否有 2 个较小的数字(例如),B.get(1)是否有 至少 相同的数量(因为B.get(1)>B.get(0))并且可以跳过您已经在A中签入的索引。
标签: java optimization arraylist