题目描述: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.Note:
The solution set must not contain duplicate quadruplets.
解题思路:先将数组排序,固定两个数的位置的同时避免重复,若和大于目标,则将大数左移,若和小于目标,则将小数右移,若和等于目标,将这四个数加入列表,并将小数右移大数左移(注意避免重复)。
代码如下:
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
if(nums==null||nums.length<4) return result;
for(int i=0;i<nums.length-3;i++){
if(i>0&&nums[i]==nums[i-1]) continue;
for(int j=i+1;j<nums.length-2;j++){
if(j>(i+1)&&nums[j]==nums[j-1]) continue;
int low=j+1,high=nums.length-1;
int sum = target-nums[i]-nums[j];
while(low<high){
if(nums[low]+nums[high]==sum){
result.add(Arrays.asList(nums[i],nums[j],nums[low],nums[high]));
while(low<high&&nums[low]==nums[low+1]) low++;
while(low<high&&nums[high]==nums[high-1]) high--;
low++;
high--;
}else if(nums[low]+nums[high]<sum) low++;
else high--;
}
}
}
return result;
}
}
博客围绕四数之和问题展开,给定含n个整数的数组nums和整数target,需找出数组中所有和为target的唯一四元组。解题思路是先对数组排序,固定两个数位置并避免重复,根据和与目标值大小关系移动指针。还给出了相应Java代码。

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



