4Sum
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.
时间复杂度:O(n^3)
空间复杂度:O(1)
三个数的时候,当确定第一个数字后,第一个数字能不与其前一个的数字相同,否则结果一定重复。
四个数的时候,确定第一个数字后,也要保证第一个数字不能与其前一个数字相同,但是第二个数没有该限制,即可以存在第一个数 = 第二个数的情况 (但是要保证j - i != 1 时,第二个数不能和前面的重复)
特殊用例:
1.{0,0,0,0}
2.{-1,0,0,0,0,1}
3.{-1,-1,-1,-1,3}
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
int length = nums.length;
if(length < 4)
return new ArrayList<>();
Arrays.sort(nums);
List<List<Integer>> resultList = new ArrayList<>();
for(int i = 0;i < length - 3;i++){
if(i > 0 && nums[i] == nums[i - 1]){
continue;
}
for(int j = i + 1;j < length - 2;j++){
if(nums[j] == nums[j - 1] && j - i != 1){
continue;
}
int tempSum = nums[i] + nums[j];
int start = j + 1;
int end = length - 1;
while(start < end){
int temp = tempSum;
temp = temp + nums[start] + nums[end];
if(temp == target){
resultList.add(Arrays.asList(nums[i],nums[j],nums[start],nums[end]));
start++;
end--;
while(start < end && nums[start] == nums[start - 1]){
start++;
}
while(start < end && nums[end] == nums[end + 1]){
end--;
}
}else if(temp > target){
end--;
}else{
start++;
}
}
}
}
return resultList;
}
}