0018. 4Sum (M)

4Sum (M)

题目

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b+ c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

题意

求四元组使其之和等于指定值。

思路

仿照 0015. 3Sum 的方法:先对数组排序,依次固定前两个元素i、j,对后两个元素m、n使用two pointers,注意去除重复值,时间复杂度为\(O(N^3)\)

另一种方法:先预处理两个数的和,存入hash表中,再重新二重循环求两数的和sum,看能否在hash表中找到值为target-sum的key,理论上复杂度为\(O(N^2)\),但考虑到去重步骤,实际时间还会增加。


代码实现

Java

Two Pointers

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 3; i++) {
            // 去除重复的i
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < nums.length - 2; j++) {
                // 去除重复的j
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int m = j + 1, n = nums.length - 1;
                while (m < n) {
                    int sum = nums[i] + nums[j] + nums[m] + nums[n];
                    if (sum < target) {
                        m++;
                        while (m < n && nums[m] == nums[m - 1]) {
                            m++;
                        }
                    } else if (sum > target) {
                        n--;
                        while (m < n && nums[n] == nums[n + 1]) {
                            n--;
                        }
                    } else {
                        List<Integer> quaternion = new ArrayList<>();
                        quaternion.add(nums[i]);
                        quaternion.add(nums[j]);
                        quaternion.add(nums[m]);
                        quaternion.add(nums[n]);
                        ans.add(quaternion);
                        m++;
                        while (m < n && nums[m] == nums[m - 1]) {
                            m++;
                        }
                        n--;
                        while (m < n && nums[n] == nums[n + 1]) {
                            n--;
                        }
                    }
                }
            }
        }
        return ans;
    }
}

Hash

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        Map<Integer, List<Pair>> hash = new HashMap<>();
        Arrays.sort(nums);
        // 生成hash表
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                // 若hash中存在
                if (hash.containsKey(nums[i] + nums[j])) {
                    boolean flag = true;
                    // 同元素组成的sum只保留x最大的下标对
                    for (Pair pair : hash.get(nums[i] + nums[j])) {
                        if (nums[pair.x] == nums[i]) {
                            pair.x = i;
                            pair.y = j;
                            flag = false;
                            break;
                        }
                    }
                    if (flag) {
                        hash.get(nums[i] + nums[j]).add(new Pair(i, j));
                    }
                } else {
                    List<Pair> pair = new ArrayList<>();
                    pair.add(new Pair(i, j));
                    hash.put(nums[i] + nums[j], pair);
                }
            }
        }

        for (int i = 0; i < nums.length - 3; i++) {
            // 去除重复的i
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < nums.length - 2; j++) {
                // 去除重复的j
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int sum = nums[i] + nums[j];
                if (hash.containsKey(target - sum)) {
                    for (Pair pair : hash.get(target - sum)) {
                        // 只记录下标排在j后面的元素
                        if (pair.x > j) {
                            List<Integer> quaternion = Arrays.asList(nums[i], nums[j], nums[pair.x], nums[pair.y]);
                            ans.add(quaternion);
                        }
                    }
                }
            }
        }
        return ans;
    }

    private class Pair {
        int x, y;

        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
}

JavaScript

Two Pointers

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[][]}
 */
var fourSum = function (nums, target) {
  let res = []
  nums.sort((a, b) => a - b)
  for (let i = 0; i < nums.length - 3; i++) {
    if (i > 0 && nums[i] === nums[i - 1]) continue
    for (let j = i + 1; j < nums.length - 2; j++) {
      if (j > i + 1 && nums[j] === nums[j - 1]) continue
      let k = j + 1, m = nums.length - 1
      while (k < m) {
        let sum = nums[i] + nums[j] + nums[k] + nums[m]
        if ((k > j + 1 && nums[k] === nums[k - 1]) || sum < target) {
          k++
        } else if ((m < nums.length - 1 && nums[m] === nums[m + 1]) || sum > target) {
          m--
        } else {
          res.push([nums[i], nums[j], nums[k++], nums[m--]])
        }
      }
    }
  }
  return res
}

Hash

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[][]}
 */
var fourSum = function (nums, target) {
  let res = []
  let map = new Map()
  nums.sort((a, b) => a - b)

  for (let i = 0; i < nums.length - 1; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      let sum = nums[i] + nums[j]
      if (map.has(sum)) {
        let pair = map.get(sum).find((pair) => nums[pair[0]] == nums[i])
        if (pair) {
          [pair[0], pair[1]] = [i, j]
        } else {
          map.get(sum).push([i, j])
        }
      } else {
        map.set(sum, [[i, j]])
      }
    }
  }

  for (let i = 0; i < nums.length - 1; i++) {
    if (i > 0 && nums[i] === nums[i - 1]) continue
    for (let j = i + 1; j < nums.length; j++) {
      if (j > i + 1 && nums[j] === nums[j - 1]) continue
      let sum = nums[i] + nums[j]
      if (map.has(target - sum)) {
        for (let pair of map.get(target - sum)) {
          if (pair[0] > j) {
            res.push([nums[pair[0]], nums[pair[1]], nums[i], nums[j]])
          }
        }
      }
    }
  }

  return res
}
posted @ 2020-06-21 03:31  墨云黑  阅读(112)  评论(0编辑  收藏  举报