【问题标题】:What would be the best/average/and worst case complexity (big O) for this method?这种方法的最佳/平均/和最坏情况复杂度(大 O)是多少?
【发布时间】:2019-09-18 02:07:44
【问题描述】:
// Checks if list contains a specific elements
public boolean contains(String it) {
    int index=front;
    while(index!=-1){
        if(dataList[index].equals(it)) {
            return true;
        }
        index= nextList[index];
    }
    return false;
}

.equals() 比较方法如何影响算法复杂度?是不是从线性变成了二次?

【问题讨论】:

  • 你能定义frontdataListnextList吗?不管怎样,.equals(it) 至少是 O(lenght(it)),所以你需要乘以迭代次数。
  • 当然,如果it有一个固定的最大长度,O(length(it))就和常数时间一样...

标签: time-complexity big-o complexity-theory equals quadratic


【解决方案1】:

在分析此算法的运行时,您应该将 .equals() 作为基本步骤。计算算法运行时间的重要因素是 dataList 的大小,从这个意义上说,“it”的大小是恒定的。

最好的情况复杂度是找到第一个位置的元素,然后是O(1),最坏的情况是找到最后一个位置的元素,然后是O(n) .平均情况是通过取所有可能性(元素在位置 1 或位置 2 等等)并除以 n 给出的,形式上:

                      1+2+3+..+n/n 

这也是 O(n)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    相关资源
    最近更新 更多