【发布时间】:2020-09-02 19:08:05
【问题描述】:
下面是我的代码,我正在尝试找出我的代码的渐近运行时复杂度,但我不确定
public static int myAlgorithm(List<Integer> myList) {
if (myList.isEmpty()) {
return 0;
}
Collections.sort(myList); // Can assume the sort algorithm is merge sort
int sum = 0;
int max = myList.get(myList.size() - 1);
for (int item : myList) {
int diff = Math.abs(max - item);
sum = sum + diff;
}
return sum;
}
【问题讨论】:
-
不需要假设;应该记录
Collections.sort的复杂性。 -
请注意,您的函数效率低于预期。排序是查找集合中最大项目的一种糟糕方法。你会发现它只是扫描列表 O(n) 时间,而不是 O(n lg n) 时间。
标签: performance time-complexity complexity-theory