18 - 4Sum
Written on October 21, 2015
Tweet
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (nums == null || nums.length == 0) return result;
Arrays.sort(nums);
for (int i = 0; i + 3 < nums.length; i++) {
if (i > 0 && nums[i] == nums[i-1]) {
continue;
}
int a = nums[i];
for (int j = i + 1; j + 2 < nums.length; j++) {
if (j > i + 1 && nums[j] == nums[j-1]) {
continue;
}
int b = nums[j];
int lo = j + 1, hi = nums.length - 1;
while (lo < hi) {
if (lo > j + 1 && nums[lo] == nums[lo - 1]) {
lo ++;
continue;
}
if (hi < nums.length - 1 && nums[hi] == nums[hi + 1]) {
hi --;
continue;
}
int c = nums[lo], d = nums[hi];
if (a + b + c + d == target) {
List<Integer> list = new ArrayList<Integer>(Arrays.asList(a, b, c, d));
result.add(list);
lo ++;
hi --;
} else if (a + b + c + d < target) {
lo ++;
} else {
hi --;
}
}
}
}
return result;
}
}
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
if not nums:
return []
nums.sort()
ret = []
for i in range(len(nums) - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, len(nums) - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
lo, hi = j + 1, len(nums) - 1
while lo < hi:
if lo > j + 1 and nums[lo] == nums[lo - 1]:
lo += 1
continue
if hi < len(nums) - 1 and nums[hi] == nums[hi + 1]:
hi -= 1
continue
total = nums[i] + nums[j] + nums[lo] + nums[hi]
if total == target:
ret.append([nums[i], nums[j], nums[lo], nums[hi]])
lo += 1
hi -= 1
elif total > target:
hi -= 1
else:
lo += 1
return ret