算法内容
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/4sum
算法思想
该算法适合应用双指针算法思想,与前面“三数之和”和“最接近三数之和”的思想类似。这里以几张图片来详细讲解一下:
- 先将无序的数组通过Arrays.sort()的方法进行排序。
- 双指针算法思想图解
整体算法
- 双指针思想
public class Day_22 {
static Scanner input=new Scanner(System.in);
static List<List<Integer>> lists=new ArrayList<>();
public static List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
int count=nums.length-3;
int y=0;
for (int i = 0; i < count; i++) {
if (i>0&&nums[i]==nums[i-1]){
continue;
}
for (int j = i+1; j <= count; j++) {
if (j>i+1&&nums[j]==nums[j-1]){
continue;
}
y=j+1;
for (int k = nums.length-1; k >y ; ) {
if (k<nums.length-1&&nums[k]==nums[k+1]){
k--;
continue;
}
if (nums[i]+nums[j]+nums[k]+nums[y]==target){
List<Integer> list=new ArrayList<>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[k]);
list.add(nums[y]);
lists.add(list);
k--;
y++;
}
if (nums[i]+nums[j]+nums[k]+nums[y]>target) {
k--;
}
if (nums[i]+nums[j]+nums[k]+nums[y]<target) {
y++;
}
}
}
}
return lists;
}
public static void main(String[] args) {
System.out.print("请输入数组大小:");
int num=input.nextInt();
int [] nums=new int[num];
System.out.println("请输入数组数据:");
for (int i = 0; i < num; i++) {
System.out.println("数字"+i+":");
nums[i]=input.nextInt();
}
System.out.print("输入目标值:");
int target=input.nextInt();
System.out.println(fourSum(nums,target));
}
}
尾语
以上属于个人见解,有好的想法可以在下方评论写出自己的想法,大家一起进步。该题是力扣上的题,若有侵权,请及时告知。该题链接:https://leetcode-cn.com/problems/4sum