统计两个ArrayList A 和 B,计算A中小于B中每个数的值的数量。

huangapple go评论56阅读模式
英文:

count two arraylist A and B and count values in A which are less than each num of B

问题

给定两个ArrayList A 和 B,A={3,4,5],B=[4,7],统计在A中有多少个数字小于或等于B中的每个元素。在这个案例中,B.get(0)=4 有2个值小于或等于A,即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);
    }
}

有没有办法优化这段代码?请帮助。

英文:

Given two arraylist A and B, A={3,4,5] and B=[4,7], count how many numbers in A are less or equal than each element in B. In this case B.get(0)=4 is has 2 values less or equal in A,i.e 3 and 4, similarly 7 has 3 values. So the function should return list=[2,3].
I have solved this question using two for loops, which works for smaller inputs ,however as the size grows the performance is degraded.

import java.util.*;
public class checkDiff{
public static void check(List&lt;Integer&gt; A, List&lt;Integer&gt; B) {
    List&lt;Integer&gt; result=new ArrayList&lt;Integer&gt;();
    for(int i=0;i&lt;B.size();i++){
        int count=0;
        for(int j=0;j&lt;A.size();j++){
            if(A.get(j)&lt;=B.get(i)){
                 count++;
            }           
        }
    result.add(i,count);
    }
   for(int x:result){
    System.out.println(x);
   }

}

 public static void main(String []args){
     List&lt;Integer&gt; A=new ArrayList&lt;Integer&gt;();
     List&lt;Integer&gt; B=new ArrayList&lt;Integer&gt;();
    A.add(3);
    A.add(4);
    A.add(7);
    B.add(4);
    B.add(7);
    check(A,B);
    
 }
 }

Is there any way to optimize this code.Please help.

答案1

得分: 0

问题在于您正在处理一个未按值排序的数组。因此,您将不得不检查所有可能的组合,除非您使用已排序的列表或使用类似二叉搜索树的数据结构,否则您无法加速此过程。

英文:

The thing is that you are taking an array which is not sorted value wise. Hence you will have to check all the possible combinations and you cannot make this process faster unless and until you use a sorted list or use data structure like binary search tree.

huangapple
  • 本文由 发表于 2020年8月13日 22:11:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63397071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定