【问题标题】:What is the asymptotic runtime complexity of my code?我的代码的渐近运行时复杂度是多少?
【发布时间】: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


【解决方案1】:

假设你使用的排序是归并排序,那么算法的无症状运行时间是O(NlogN)

最复杂的步骤是排序步骤。

之后的代码大约是 O(N);寻找最大值时 1 个循环和 1 个直通。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    相关资源
    最近更新 更多