I have a method i wrote to find the duplicates in a List. It works fine but im concerned about the complexity of using containsKey. 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) ?
Here 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 to call it i do 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);
//output will be 3 and 6 clearly.
update: i re-wrote the function to just use a set which makes more sense:
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);
}
}
}