I've an array of string, I want to find the duplicat开发者_开发问答e strings in the array and want to make the duplicates null by using HashMap with a good time complexity.
Sounds like you want to use a Set. This clears all duplicate entries, but you can also just create an array which has the 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()]);
You don't actually need a map. Here's an example that uses a HashSet
instead. (Assuming that you want the repeated strings "nulled" out.
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));
You can do it in O(n)
time, by iterating over your array once, sticking every new element into a HashSet
and replacing array elements that are already in the HashSet
with nulls
.
Instead of a HashMap you can use a Set too, the steps are (you can work the details out yourself):
- for every string in the array
- if the string exists in the Map/Set null it
- otherwise add it to the Map/Set
That's it.
精彩评论