【问题标题】:count two arraylist A and B and count values in A which are less than each num of B计算两个数组列表 A 和 B 并计算 A 中小于每个 B 数量的值
【发布时间】: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


【解决方案1】:

问题是您正在使用一个未按值排序的数组。因此,您必须检查所有可能的组合,除非您使用排序列表或使用二叉搜索树等数据结构,否则您无法加快此过程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 2015-12-05
    相关资源
    最近更新 更多