算法第五天 —— 四数相加

71 阅读1分钟

四数相加II

给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足: 0 <= i, j, k, l < n nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0

解题思路:

  • 将这四个数组分成2组,第一组两两相加,将不一样值存在map[两数之和,次数]
  • 遍历第二组数组,检查map的key中是否存在0-第一组的两数之和,如果存在获取map中的次数并加起来。
public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
    HashMap<Integer, Integer> map = new HashMap<>();
    int temp = 0;
    int res = 0;
    // 统计前两次的加的结果与次数
    for (int i = 0; i < nums1.length; i++) {
        for (int j = 0; j < nums2.length; j++) {
            temp = nums1[i] + nums2[j];
            if (map.containsKey(temp)) {
                map.put(temp, map.get(temp) + 1);
            } else {
                map.put(temp, 1);
            }
        }
    }

    // 统计后两个的结果与次数

    for (int i = 0; i < nums3.length; i++) {
        for (int j = 0; j < nums4.length; j++) {
            temp = nums3[i] + nums4[j];
            if (map.containsKey(0 - temp)) { // 检查是否存有
                res += map.get(0 - temp);
            }
        }
    }
    return res;
}