相关标签
一、题目要求
二、题解和代码实现
1.题解
2.代码实现
代码如下(示例):
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
ArrayList<List<Integer>> list = new ArrayList<>();
if (nums.length<4){
return list;
}
Arrays.sort(nums);//排序
for (int i = 0; i < nums.length; i++) {//先用i指针锁定第一个元素
if (i>0 && nums[i]==nums[i-1]){//去重
continue;
}
int val= nums[i];
int end = i+1;//第二个元素的指针
while (end <nums.length){//锁定第二个元素
if (end>i+1 && nums[end] == nums[end-1]){//去重
end++;
continue;
}
int state =end+1;//第三个元素指针
int end1 =nums.length-1;//第四个元素指针
while (state < end1){//寻找第三第四个元素
int sum= val+nums[end]+nums[state]+nums[end1];
if (sum==target){//符合条件
list.add(Arrays.asList(val,nums[end],nums[state],nums[end1]));
while (state <end1 && nums[state]==nums[state+1]){//去重
state++;
}
while (state <end1 && nums[end1] == nums[end1-1]){//去重
end1--;
}
state++;
end1--;
}else if (sum>target){//缩小范围
end1--;
}else {//缩小范围
state++;
}
}
end++;//移动第二个指针
}
}
return list;
}
}