kSum 泛指一類問題碉熄,例如 leetcode 第1題 2 Sum腹忽,leetcode 第15題 3 Sum饰序,leetcode 第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循環(huán)解法(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 循環(huán)肯定會超時。因此我們還是先排序绑洛,然后再用 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(N2),最終復雜度為O(N2)
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 題的時候我們先固定了一個數(shù)num真屯,然后再在剩余的數(shù)組元素中利用 two pointers 方法尋找和為 target - num的兩個數(shù)脸候。
歸納分析,我們可以將 kSum 一類的問題的解法分為兩個步驟:
- 將 kSum 問題轉換成 2Sum 問題
- 解決 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(N^3)。