题目描述:

方法1:暴力枚举法
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> list = new ArrayList<List<Integer>>();
for(int first = 0; first < nums.length; ++first) {
if(first > 0 && nums[first] == nums[first - 1]) {
continue;
}
for(int second = first + 1; second < nums.length; ++second) {
if(second > first + 1 && nums[second] == nums[second - 1]) {
continue;
}
for(int third = second +1; third < nums.length; ++third) {
if(third > second + 1 && nums[third] == nums[third - 1]) {
continue;
}
int forth = nums.length - 1;
while(third < forth && nums[first] + nums[second] + nums[third] + nums[forth] > target) {
forth--;
}
if(third == forth) {
continue;
}
if(nums[first] + nums[second] + nums[third] + nums[forth] == target) {
List<Integer> l = new ArrayList<Integer>();
l.add(nums[first]);
l.add(nums[second]);
l.add(nums[third]);
l.add(nums[forth]);
list.add(l);
}
}
}
}
return list;
}
}

方法2:双指针,对暴力枚举法进行了改进
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> quadruplets = new ArrayList<List<Integer>>();
if (nums == null || nums.length < 4) {
return quadruplets;
}
Arrays.sort(nums);
int length = nums.length;
for (int i = 0; i < length - 3; i++) {
if (i > 0 && 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;
}
for (int j = i + 1; j < length - 2; j++) {
if (j > i + 1 && 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;
}
int left = j + 1, right = length - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
quadruplets.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
left++;
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
return quadruplets;
}
}

- 时间复杂度:O(n³)
- 空间复杂度:O(n)
本文介绍了求解四数之和问题的两种方法:暴力枚举法和改进后的双指针法。通过这两种方法,文章详细阐述了如何寻找数组中四个数相加等于特定目标值的所有组合,并分析了其时间复杂度为O(n³)。
&spm=1001.2101.3001.5002&articleId=120394944&d=1&t=3&u=f37a08a3b8244bd685f2cd6f47608d4b)
2010

被折叠的 条评论
为什么被折叠?



