优化(在速度方面)
Optimization (in terms of speed )
有没有其他方法可以优化此代码。任何人都可以想出更好的方法,因为这会在主代码中花费大量时间。非常感谢;)
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]
重复:[C/SEA。java,aep,aeP,C/SEA。java]
不重复:[A/tea、C/clock]
“很多时间”是多少时间?您输入的内容是否比您实际向我们展示的内容更大?
您 可以 将其与 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);
中的算法可以使用多线程加速执行。
这理论上可以将处理时间减少 M,其中 M 是您的系统可以处理的最大线程数运行并发。然而,由于 M 是一个常数,这不会改变复杂度的顺序,因此仍然是 O(N).
乍看之下,我恐怕在 O(N) 之内找不到解决您问题的方法。
有没有其他方法可以优化此代码。任何人都可以想出更好的方法,因为这会在主代码中花费大量时间。非常感谢;)
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]
重复:[C/SEA。java,aep,aeP,C/SEA。java]
不重复:[A/tea、C/clock]
“很多时间”是多少时间?您输入的内容是否比您实际向我们展示的内容更大?
您 可以 将其与 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);
这理论上可以将处理时间减少 M,其中 M 是您的系统可以处理的最大线程数运行并发。然而,由于 M 是一个常数,这不会改变复杂度的顺序,因此仍然是 O(N).
乍看之下,我恐怕在 O(N) 之内找不到解决您问题的方法。