Leetcode.18四数之和
题目难度:中等
题目:原题链接
思路:
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;
}
//如果四个数之和大于target直接跳出,对于增序后面更不会满足条件
if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
break;
}
//和小于target,需要i往后加
if (nums[i] + nums[length - 3] + nums[length - 2] + nums[length - 1] < target) {
continue;
}
//从i位置往后遍历j找合适的
for (int j = i + 1; j < length - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
//和大于target直接跳出
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;
}
}