JAVA
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<>();
for (int n = 0; n < nums.length - 3; n++) {
if (n > 0 && nums[n] == nums[n - 1]) continue;
if (nums[n] + nums[n + 1] + nums[n + 2] + nums[n + 3] > target) break;
for (int m = n + 1; m < nums.length - 2; m++) {
if (nums[m] == nums[m - 1] && m > (n + 1)) continue; //避免二次重复
if (nums[n] + nums[m] + nums[m + 1] + nums[m + 2] > target) break;
int i = m + 1, j = nums.length - 1;
while (i < j) {
int sum = nums[n] + nums[m] + nums[i] + nums[j];
if (sum == target) {
ans.add(Arrays.asList(nums[n], nums[m], nums[i], nums[j]));
while (i < j && nums[j] == nums[--j]) ;
while (i < j && nums[i] == nums[++i]) ;
} else if (sum > target) {
while (i < j && nums[j] == nums[--j]) ;
} else {
while (i < j && nums[i] == nums[++i]) ;
}
}
}
}
return ans;
}
}
Python
t
r
i
p
l
e
triple
triple 三倍
q
u
a
d
r
u
p
l
e
quadruple
quadruple 四倍
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
quadruplets = list() # 这种方式也可以创建列表
nums.sort()
length = len(nums)
for i in range(length - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
if nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target:
break
if nums[i] + nums[length - 3] + nums[length - 2] + nums[length - 1] < target:
continue # 相比上面的 JAVA多了这类判断条件
for j in range(i + 1, length - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
if nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target:
break
if nums[i] + nums[j] + nums[length - 2] + nums[length - 1] < target:
continue
left, right = j + 1, length - 1
while left < right:
sum = nums[i] + nums[j] + nums[left] + nums[right]
if sum == target:
quadruplets.append([nums[i], nums[j], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]:
left += 1
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
right -= 1
elif sum < target:
left += 1
else:
right -= 1
return quadruplets