【问题标题】:Time complexity of while inside for loop?for循环内部while的时间复杂度?
【发布时间】:2021-02-05 21:38:28
【问题描述】:

我有以下算法:

for(int i=0; i<list.size(); i++){
 String cur = list.get(i);
 int cnt =0;
 while(output.contains(cur)){
  cur= cur.substring(0,5) + String.valueOf(cnt);
  cnt++;
 }
 output.add(cur);
}

“列表”和“输出”并不是 ArrayList。

我认为时间复杂度是 O(n^2)。但是内部有 output.contains(cur) 的 while 循环呢?

【问题讨论】:

    标签: java loops time-complexity


    【解决方案1】:

    这个算法的复杂度似乎取决于output列表的初始内容:

    • output为空,while循环不执行,复杂度为O(N),其中N为list的大小

    • listoutput 的设计符合 output.contains(cur) 条件 例如,

    List<String> list = Arrays.asList("abcde0", "abcde1", "abcde2", "abcde3", "abcde4", "abcde5", "abcde6");
    List<String> output = new ArrayList<>(list);
    

    output 的大小将不断增长,因此迭代次数将如下所示:

    1) n+1
    2) n+1 + n+2 = 2 (n+1) + 1
    3) n+1 + n+2 + n+3 = 3 (n+1) + 3
    4) n+1 + n+2 + n+3 + n+4 = 4 (n+1) + 6
    ...
    n) n (n+1) + (1 + n-1)*(n-1)/2 = n (n+1) + n (n - 1)/2 = n (3n + 1)/2 
    

    因此,在这种情况下(可能不是最坏的情况),复杂度可能是 O(N^2)。

    【讨论】:

    • 嗨,亚历克斯,感谢您的回答!我应该认为 contains() 方法需要 O(n) 吗?还是只有迭代很重要?
    • 对,我完全忽略了在列表中进行线性搜索。
    猜你喜欢
    • 2015-02-16
    • 2023-02-09
    • 1970-01-01
    • 2013-12-08
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多