有大佬可以分享下最佳题解吗
总感觉我这个还不太行。
public class Main {
public static void main(String[] args) {
int[] arr1 = {1, 2, 2, 3};
int[] arr2 = {2, 3};
int test = new Solution().test(arr1, arr2);
System.out.println(test);//12
}
}
class Solution {
public int test(int[] nums1, int[] nums2) {
int sum = 0;
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < nums1.length; i++) {
hashMap.put(nums1[i], hashMap.getOrDefault(nums1[i], 0) + 1);
}
for (int i = 0; i < nums2.length; i++) {
hashMap.put(nums2[i], hashMap.getOrDefault(nums2[i], 0) + 1);
}
for (Map.Entry<Integer, Integer> entry : hashMap.entrySet()) {
if (entry.getValue() > 1) sum += entry.getKey() * entry.getValue();
}
return sum;
}
}