此代碼需要 O(n) 時間和 O(n) 空間是否有任何其他方法可以優化此代碼。我在考慮多執行緒。任何人都可以想出更好的方法,因為這在主代碼中花費了大量時間。非常感謝;)
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);
}
}
輸出:Dup- [C, trump tower, C, trump Tower] nonDup- [A, hmm's, CAP, hmm]
uj5u.com熱心網友回復:
“很多時間”是多少時間?您的輸入是否比您實際向我們展示的更大?
您可以將其與類似的東西并行化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);
uj5u.com熱心網友回復:
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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/452675.html
上一篇:從在執行緒中運行的函式訪問while回圈變數并在C#中的其他函式中使用
下一篇:一次停止多個執行緒
