Leetcode kSum問題

kSum 泛指一類問題,例如 leetcode 第1題 2 Sumleetcode 第15題 3 Sumleetcode 第18題 4 Sum數組

咱們先一題一題來看,而後總結出這一類題目的解題套路。bash

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)ide

這種解法最簡單直觀,可是效率也是最低的。若是提交的話沒法經過全部 test case,確定會超時。ui

排序+two pointers(O(NlogN))

先排序,而後再使用 two pointers:spa

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))code

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)three

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的兩個數。ip

概括分析,咱們能夠將 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)

相關文章
相關標籤/搜索