题目地址:4Sum
题目简介:
给定一个包含n个整数的数组nums和一个目标值target,判断nums中是否存在四个元素a,b,c,d,使得a+b+c+d的值与target相等?找出所有满足条件且不重复的四元组。
注意答案中不可以包含重复的四元组。
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]
]
题目解析:3数相加的加强版,那就老法子走新路
C++版:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> ans_set;
if (nums.size() <= 3)
{
return ans_set;
}
sort(nums.begin(), nums.end());
for(int j = 0; j <= nums.size() - 4; j++)
{
if (j > 0 && nums[j] == nums[j - 1]) continue;
for (int i = j + 1; i < nums.size() - 2; i++)
{
if (i > j + 1 && nums[i] == nums[i - 1]) continue;
int l = i + 1, r = nums.size() - 1;
while(l < r)
{
if (nums[i] + nums[l] + nums[r] > target - nums[j]) r--;
else if (nums[i] + nums[l] + nums[r] < target - nums[j]) l++;
else
{
ans_set.push_back({nums[j],nums[i], nums[l], nums[r]});
while(l < r && nums[l] == nums[l + 1]) l++;
while(l < r && nums[r] == nums[r - 1]) r--;
l++;
r--;
}
}
}
}
return ans_set;
}
};
Python版:
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
ans_list = []
if (len(nums) <= 3): #如果当前的数字少于三个那么直接返回结果
return (ans_list)
nums.sort()
for j in range(0,len(nums) - 3):
if (j > 0 and nums[j] == nums[j - 1]):
continue
for i in range(j + 1,len(nums) - 2):
if (i > j + 1 and nums[i] == nums[i - 1]):
continue
l = i + 1
r = len(nums) - 1
while (l < r):
if (nums[i] + nums[l] + nums[r] + nums[j] == target):
ans_list.append([nums[j],nums[i],nums[l],nums[r]])
while (l < r and nums[l] == nums[l + 1]):
l += 1
while (l < r and nums[r] == nums[r - 1]):
r -= 1
l += 1
r -= 1
elif (nums[i] + nums[l] + nums[r] > target - nums[j]):
r -=1
else:
l += 1
return (ans_list)