繁体   English   中英

从第一个列表中查找最小元素

[英]Finding minimum element from first list

我有一个 function 以 2 List 作为参数。 我们想要的最终结果是从第一个列表中检查,有多少元素小于等于第二个列表中的每个元素?

例如:

firstlist = [1,4,2,4]
secondList = [3,5]

Output = [2,4]
解释:
secondList[3] >= firstList[1,2] 所以总数是 2。 secondList[5] >= firstList[1,4,2,4] 所以总数是 4。

我已经写了一个解决方案,但这不是优化的。

   public  List<Integer> counts(List<Integer> teamA, List<Integer> teamB) {
       // Write your code here
       int[] b = teamB.stream().mapToInt(i -> i).toArray();
       int[] a = teamA.stream().mapToInt(i -> i).toArray();
       int counter;
       List<Integer> goals = new ArrayList<>();
       for (int i= 0;i<b.length;i++){
           counter= 0;
           for (int j =0;j < a.length; j++){
               if (a[j] <= b[i]){
                   counter++;
               }
           }
           goals.add(counter);
       }
       return goals;

   }

如果您想降低时间复杂度,那么您可以对第一个列表进行排序,然后对第二个列表中的每个元素应用二分查找来查找较少的数字。

这样,时间复杂度将从O(N*M)降低到O(Mlog(N))

使用流来简化您的代码。 如果您使用列表,请坚持使用列表。 Arrays 通常更快但更难处理。

public static List<Integer> counts(List<Integer> teamA, List<Integer> teamB) {
    //Stream teamB and map each value to a result
    return teamB.stream().map(b -> 
        //Result is count of elements from teamA that are <= b
        (int) teamA.stream().filter(a -> a <= b).count()
    ).collect(Collectors.toList()); //Collect result stream into a list
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM