How to find duplicate row array entries and make them null using HashMap

I have an array of strings, I want to find duplicate strings in the array and want to make duplicates null using a HashMap with good time complexity.

+3
source share
4 answers

Looks like you want to use Set. This clears all duplicate entries, but you can also just create an array that has unique entries (and no null values)

String[] array =
Set<String> found = new LinkedHashSet<String>();
for(int i=0;i<array.length;i++)
   if(!found.add(array[i]))
       array[i] = null;

// just the entries without duplicates.
String[] unique = found.toArray(new String[found.size()]);
+4
source

In fact, you do not need a map. Here is an example that uses instead HashSet. (Assuming you want duplicate lines to be "muted".

String[] strs = "aa,bb,cc,aa,xx,cc,dd".split(",");

Set<String> seen = new HashSet<String>();

for (int i = 0; i < strs.length; i++)
    if (!seen.add(strs[i]))
        strs[i] = null;

// Prints [aa, bb, cc, null, xx, null, dd]
System.out.println(Arrays.toString(strs));
+2
source

O(n) , , HashSet , HashSet nulls.

+1

Instead of HashMap, you can also use Set, steps (you can process the details yourself):

  • for each row in the array
  • if the string exists in Map / Set null it
  • otherwise add it to Map / Set

What is it.

0
source

All Articles