gpt4 book ai didi

java - hashmap 包含键复杂度

转载 作者:搜寻专家 更新时间:2023-11-01 04:05:38 25 4
gpt4 key购买 nike

我写了一个方法来查找列表中的重复项。它工作正常但我担心使用 containsKey 的复杂性。当我们使用 containsKey 时,我们必须为每个键计算一个哈希函数,然后将每个键与我们的搜索项进行比较,对吗?那么复杂度不是 O(n) 吗?

函数如下:

public void findDup(List<String> list){

HashMap<String,Integer> map = new HashMap<>();
int pos=0;
for(String s: list){
if(map.containsKey(s)){
Log.v("myapp","duplicate found:"+s);
}
else
map.put(s,pos);
pos++;
}
}

我这样调用它:

List<String>list=new ArrayList<>();

for(int i=0;i<12;i++)
list.add(i+"");

//these numbers should surely be duplicates
list.add("3");list.add("6");

findDup(list);

//明确输出3和6。

更新:我重新编写了函数以仅使用一个更有意义的集合:

public void findDup(List<Integer> list){

HashSet<Integer> set = new HashSet<>();
for(Integer num: list){
if(!set.add(num)){
Log.v("myapp","duplicate found:"+num);
}

}
}

最佳答案

它在 Javadoc 中指定为 O(1)。

您的算法的复杂度因此为O(N)。

但即使没有 containsKey() 调用,这实际上也是不必要的。您所要做的就是测试 put() 是否返回一个非空值,这表示重复。

When we use containsKey we have to compute a hash function for every key and then compare against each with our search item, right?

错了。我们计算搜索键的哈希值并检查该桶是否被相等的键占用。

So wouldn't the complexity be O(n) ?

没有。

关于java - hashmap 包含键复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35109986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com