This code takes O(n) time and O(n) space is there any other way to optimize this code. I was thinking about the multithread. Anyone can come up with better way because this is taking lot of time in main code. Thanks alot;)
String[] nums = {"A","C","trump tower","hmm's","CAP","C","hmm","trump Tower"};
HashMap<String, Integer> hmap = new HashMap<String, Integer>();
List<String> dup = new ArrayList<String>();
List<String> nondup = new ArrayList<String>();
for (String num : nums) {
String x= num;
String result = x.toLowerCase();
if (hmap.containsKey(result)) {
hmap.put(result, hmap.get(result) 1);
}
else {
hmap.put(result,1);
}
}
for(String num:nums){
int count= hmap.get(num.toLowerCase());
if (count == 1){
nondup.add(num);
}
else{
dup.add(num);
}
}
Output: Dup- [C, trump tower, C, trump Tower] nonDup- [A, hmm's, CAP, hmm]
CodePudding user response:
How much time is "a lot of time"? Is your input bigger than what you've actually shown us?
You could parallelize this with something like Arrays.parallelStream(nums).collect(Collectors.groupingByConcurrent(k -> k, Collectors.counting())
, which would get you a Map<String, Long>
, but that would only speed up your code if you have a lot of input, which it doesn't look like you have right now.
You could parallelize the next step, if you liked, like so:
Map<String, Long> counts = Arrays.parallelStream(nums)
.collect(Collectors.groupingByConcurrent(k -> k, Collectors.counting());
Map<Boolean, List<String>> hasDup =
counts.entrySet().parallelStream()
.collect(Collectors.partitioningBy(
entry -> entry.getValue() > 1,
Collectors.mapping(Entry::getKey, Collectors.toList())));
List<String> dup = hasDup.get(true);
List<String> nodup = hasDup.get(false);
CodePudding user response:
Set<String> hash_Set = new HashSet<String>();
List<String> dup = new ArrayList<String>();
List<String> nondup = new ArrayList<String>();
for(String num:nums)
{
if(hash_Set.add(num)){
nondup.add(num);
}
else{
dup.add(num);
}
}