还有其他方法来优化这段代码吗。任何人都可以想出更好的方法,因为这需要花费大量的时间在主代码中。非常感谢;)
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);
}
}输出: A/tea,C/SEA.java,C/clock,aep,aeP,C/SEA.java
Dups: C/SEA.java,aep,aeP,C/SEA.java
无障碍: A/tea,C/clock
发布于 2022-03-29 21:54:17
“很多时间”是多长时间?你的投入比你实际向我们展示的要大吗?
您可以使用类似于Arrays.parallelStream(nums).collect(Collectors.groupingByConcurrent(k -> k, Collectors.counting())的东西并行处理,这将为您提供一个Map<String, Long>,但是只有当您有大量的输入时,这才会加快代码的速度,而这看起来并不像现在这样。
如果您愿意,可以将下一步并行化,如下所示:
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);发布于 2022-03-31 21:32:31
other answers中的算法可以使用多个线程加速执行。
理论上,这可以减少处理时间,其因子为M,其中M是系统可以并发运行的最大线程数。然而,由于M是一个恒数,这并不改变复杂性的顺序,因此它仍然是O(N)。
乍一看,我恐怕找不到解决你问题的办法。
https://stackoverflow.com/questions/71669167
复制相似问题