【双指针】LeetCode 18. 四数之和
题目链接
思路
与 【双指针】LeetCode 15. 三数之和 思路相似,但是要注意测试用例可能溢出,需要转换为 long
代码
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
for(int a = 0; a < nums.length - 3; a++){
if(a > 0 && nums[a] == nums[a - 1]){
continue;
}
for(int b = a + 1; b < nums.length - 2; b++){
if(b > a + 1 && nums[b] == nums[b - 1]){
continue;
}
int c = b + 1;
int d = nums.length - 1;
while(c < d){
long sum = (long)nums[a] + (long)nums[b] + (long)nums[c] + (long)nums[d];
if(sum == target){
result.add(Arrays.asList(nums[a], nums[b], nums[c], nums[d]));
while(c < d && nums[c + 1] == nums[c]){
c++;
}
while(c < d && nums[d - 1] == nums[d]){
d--;
}
c++;
d--;
}else if(sum > target){
d--;
}else{
c++;
}
}
}
}
return result;
}
}