【问题标题】:Finding minimum element from first list从第一个列表中查找最小元素
【发布时间】:2021-05-13 02:39:55
【问题描述】:

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

例如:

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

输出 = [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;

   }

【问题讨论】:

  • 它给出了正确的结果吗?如果不是,那是什么问题,如果确实如此,您想改进什么? (请注意,您可以直接在 teamA 和 teamB 上进行迭代,而不是仅仅为了它而创建数组)
  • 这看起来像是一个学习练习,所以最好自己尝试一下。从 teamB 获取一个流并将每个元素映射到从 teamA 中少于它的元素的数量,然后收集回一个列表。
  • @assylias : 是的,上面是有效的,如果列表中的元素太多,则需要更长的时间,因为我们使用 for 循环并遍历每个元素
  • 您接受的解决方案(使用流)也在幕后使用了一个循环 - 复杂性是相同的,流构造最多只能执行相同的操作。

标签: java optimization java-8


【解决方案1】:

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

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

【讨论】:

  • +1 获取实际优化建议。我相信它应该是O(N logN) + O(M logN),因此最坏的情况是max(O(N logN), O(M logN))
【解决方案2】:

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

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    相关资源
    最近更新 更多