kSum问题

2018/12/25 算法 leetcode

kSum 泛指一类问题,例如 leetcode 第1题 2 Sumleetcode 第15题 3 Sumleetcode 第18题 4 Sum

我们先一题一题来看,然后总结出这一类题目的解题套路。

2Sum(leetcode 第1题)

问题

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

两层for循环解法(O(N^2))

public int[] twoSum(int[] nums, int target) {
    int[] res = new int[2];
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] == target) {
                res[0] = i;
                res[1] = j;
                return res;
            }
        }
    }
    return res;
}

时间复杂度:O(N^2)

这种解法最简单直观,但是效率也是最低的。如果提交的话无法通过所有 test case,肯定会超时。

排序+two pointers(O(NlogN))

先排序,然后再使用 two pointers:

public int[] twoSum(int[] nums, int target) {
    Arrays.sort(nums);
    int i = 0, j = nums.length - 1;
    int[] res = new int[2];
    while (i < j) {
        if (nums[i] + nums[j] == target) {
            res[0] = i;
            res[1] = j;
            break;
        } else if (nums[i] + nums[j] < target) {
            i++;
        } else {
            j--;
        }
    }
    return res;
}

时间复杂度:O(Nlog(N)) + O(N),最后复杂度为O(Nlog(N))

HashMap一遍遍历(O(N))

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }
    int j = 0, k = 0;
    for (int i = 0; i < nums.length; i++) {
        int left = target - nums[i];
        if (map.containsKey(left) && i != map.get(left)) {
            j = i;
            k = map.get(left);
            break;
        }
    }
    int[] res = new int[2];
    res[0] = j;
    res[1] = k;
    return res;
}

时间复杂度:O(N)

3Sum(leetcode 第5题)

问题

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

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

排序+ two pointers

3Sum 和 2Sum 类似,前面介绍的 2Sum 的前两种解法对 3Sum一样有效。第一种解法通过三层 for 循环肯定会超时。因此我们还是先排序,然后再用 two pointers 来解题:

public List<List<Integer>> threeSum(int[] nums) {
    if (nums == null || nums.length < 3) {
        return new ArrayList<>();
    }
    List<List<Integer>> ret = new ArrayList<>();
    Arrays.sort(nums);
    for (int i = 0; i < nums.length - 2; i++) {
        int num = nums[i];
        if (i > 0 && nums[i] == nums[i - 1]) {
            continue;
        }
        bSearch(nums, i + 1, nums.length - 1, -num, ret, i);
    }
    return ret;
}

private void bSearch(int[] nums, int start, int end, int targetTotal, List<List<Integer>> ret, int index) {
    int i = start, j = end;
    while (i < j) {
        if (targetTotal == nums[i] + nums[j]) {
            List<Integer> oneShot = new ArrayList<>();
            oneShot.add(nums[index]);
            oneShot.add(nums[i]);
            oneShot.add(nums[j]);
            ret.add(oneShot);
            // 题目要求结果返回的 triple 都是唯一的,因此这里需要跳过前后相同的元素
            while (i < j && nums[i] == nums[i + 1]) {
                i++;
            }
            while (i < j && nums[j] == nums[j - 1]) {
                j--;
            }
            i++;
            j--;
        } else if (nums[i] + nums[j] > targetTotal) {
            j--;
        } else {
            i++;
        }
    }
}

时间复杂度:O(NlogN) + O(N^2),最终复杂度为O(N^2)

4Sum(leetcode 第18题)

问题

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]
]

分析

在解 3Sum 题的时候我们先固定了一个数num,然后再在剩余的数组元素中利用 two pointers 方法寻找和为 target - num的两个数。

归纳分析,我们可以将 kSum 一类的问题的解法分为两个步骤:

  1. 将 kSum 问题转换成 2Sum 问题
  2. 解决 2Sum 问题

给出 kSum 一类问题的一般解法如下:

/**
 * All kSum problem can be divided to two parts:
 * 1: convert kSum to 2Sum problem;
 * 2: solve the 2Sum problem;
 *
 * @param k
 * @param index
 * @param nums
 * @param target
 * @return
 */
private List<List<Integer>> kSum(int k, int index, int[] nums, int target) {
    List<List<Integer>> res = new ArrayList<>();
    int len = nums.length;
    if (k == 2) {
        // 使用 two pointers 解决 2Sum 问题
        int left = index, right = len - 1;
        while (left < right) {
            int sum = nums[left] + nums[right];
            if (sum == target) {
                List<Integer> path = new ArrayList<>();
                path.add(nums[left]);
                path.add(nums[right]);
                res.add(path);
                // skip the duplicates
                while (left < right && nums[left] == nums[left + 1]) {
                    left++;
                }
                while (left < right && nums[right] == nums[right - 1]) {
                    right--;
                }
                left++;
                right--;
            } else if (sum > target) {
                right--;
            } else {
                left++;
            }
        }
    } else {
        // 将 kSum 问题转换为 2Sum 问题
        for (int i = index; i < len - k + 1; i++) {
            // 跳过重复的元素
            if (i > index && nums[i] == nums[i - 1]) {
                continue;
            }
            // 固定一个元素,然后递归
            List<List<Integer>> kSubtractOneSum = kSum(k - 1, i + 1, nums, target - nums[i]);
            if (kSubtractOneSum != null) {
                for (List<Integer> path : kSubtractOneSum) {
                    path.add(0, nums[i]); // 将固定的元素加入路径中
                }
                res.addAll(kSubtractOneSum);
            }
        }
    }
    return res;
}

解决了 kSum问题之后,4Sum 问题的解法就很简单了:

public List<List<Integer>> fourSum(int[] nums, int target) {
    if (nums == null || nums.length < 4) {
        return new ArrayList<>();
    }
    Arrays.sort(nums);
    return kSum(4, 0, nums, target);
}

时间复杂度:O(NlogN) + O(N^3),最终复杂度为:O(N^3)

Search

    Table of Contents