JAVA版本
本题的解法是使用hash表的解法,个人认为本题较难思考。
思路:我们将四个数组两两一组,求出上面两个数组的和,将他们保存到map集合当中,和作为key,出现的次数来作为value来保存,再将下面的两个数组求和,每次求和后去map集合当中去看看有没有他们和的相反数,如果有,将出现的次数记录上,没有的话就继续向下执行。
比如:nums1 与nums2 中有一个和是3,nums3与nums4中的和是-3,此时将nums3与nums4的和变为相反数,变为3,然后与集合中比较,获得3出现的次数。然后用res来将能匹配上的值记录起来。最后将res输出,便得到了我们所求的值。
class Solution {
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
int temp =0;
int res=0;
Map <Integer ,Integer> map = new HashMap<Integer,Integer>();
for(int i : nums1){
for(int j :nums2){
temp = i+j;
if(map.containsKey(temp)){
map.put(temp,map.get(temp) + 1);
}else{
map.put(temp,1);
}
}
}
for(int i : nums3){
for(int j :nums4){
temp = i+j;
if(map.containsKey(-temp)){
res += map.get(-temp);
}
}
}
return res;
}
}