Java – HashMap containskey complexity
I have a method. I write a duplicate item in the list It works well, but I'm worried about the complexity of using containskey When we use containskey, we have to calculate a hash function for each key and compare each key with our search term, right? Isn't that O (n)?
This is the function:
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++; } }
And call me doing this:
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);
//The output will be clearly displayed as 3 and 6
Update: I rewritten the function, using only a more meaningful set:
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); } } }
Solution
It is specified as O (1) in Javadoc
Therefore, the complexity of the algorithm is O (n)
But even if there is no containskey () call, this is actually unnecessary All you have to do is test whether put () returns a non - null value, indicating a duplicate
Wrong We calculate the hash value of the search keyword and check whether the bucket is occupied by equal keys
No,