【LeetCode】#18四数之和(4Sum)

【LeetCode】#18四数之和(4Sum)

题目描述

给定一个包含 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]
]

Description

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.

Example

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

解法

class Solution{
	public List<List<Integer>> fourSum(int[] nums, int target){
		List<List<Integer>> res = new ArrayList<>();
		Arrays.sort(nums);
		for(int i=0; i<nums.length-3; i++){
			for(int j=i+1; j<nums.length-2; j++){
				if(j>(i+1) && nums[j]==nums[j+1]){
					continue;
				}
				int left = j + 1;
				int right = nums.length - 1;
				while(left<right){
					int sum = nums[i] + nums[j] + nums[left] + nums[right];
					if(sum==target){
						List<Integer> list = new ArrayList<>();
						list.add(nums[i]);
						list.add(nums[j]);
						list.add(nums[left]);
						list.add(nums[right]);
						if(!res.contains(list)){
							res.add(list);
						}
						left++;
						right--;
					}else if(sum<target){
						left++;
					}else{
						right--;
					}
				}
			}
		}
		return res;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43858604/article/details/84715081