18 4 Sum + 454 4SumII

Last Updated on: January 6, 2021 pm

18 4Sum - Medium

Tags: Array / HashTable / Two Pointers

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:

1
2
3
4
5
6
7
8
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]
]

Solution

3Sum的基础上加了一层for循环.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums == null || nums.length < 4) return res;
Arrays.sort(nums);
int len = nums.length;

for(int i = 0; i < len - 3; i++){
if(i != 0 && nums[i] == nums[i - 1])
continue;
for(int j = i + 1; j < len - 2; j++){
if(j > i + 1 && nums[j] == nums[j - 1])
continue;

int left = j + 1;
int right = len - 1;
while(left < right){
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if(sum > target)
right--;
else if(sum < target)
left++;
else{
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[left]);
temp.add(nums[right]);
res.add(temp);
left++; right--;
while(left < right && nums[left] == nums[left - 1]) left++;
while(left < right && nums[right] == nums[right + 1]) right--;
}
}

}
}


return res;
}
}

454 4Sum II - Medium

Tags: Hash Map / Binary Search

Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

Output:
2

Explanation:
The two tuples are:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

Solution

利用map。
第一个和第二个的和去生成map。
然后利用第三个第四个的和去对应的单元找。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
int res = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < A.length; i++){
for(int j = 0; j < B.length; j++){
int sum = A[i] + B[j];
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
}

for(int i = 0; i < C.length; i++){
for(int j = 0; j < D.length; j++){
int sum = -(C[i] + D[j]);
if(map.containsKey(sum))
res = res + map.get(sum);
}
}
return res;
}
}