题目描述
详见3Sum思路
(排序,双指针)
排序后固定两个数,然后用双指针(left, right)去找3项, 4项
最后nums[i] + nums[j] + 3项 + 4项 = target
Python代码
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
n = len(nums)
if n < 4: return []
nums.sort()
res = []
for i in range(n-3):
# 防止重复 数组进入 res
if i > 0 and nums[i] == nums[i-1]:
continue
# 当数组最小值和都大于target 跳出
if nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target:
break
# 当数组最大值和都小于target,说明i这个数还是太小,遍历下一个
if nums[i] + nums[n-1] + nums[n-2] + nums[n-3] < target:
continue
for j in range(i+1,n-2):
# 防止重复 数组进入 res
if j - i > 1 and nums[j] == nums[j-1]:
continue
# 同理
if nums[i] + nums[j] + nums[j+1] + nums[j+2] > target:
break
# 同理
if nums[i] + nums[j] + nums[n-1] + nums[n-2] < target:
continue
# 双指针
left = j + 1
right = n - 1
while left < right:
tmp = nums[i] + nums[j] + nums[left] + nums[right]
if tmp == target:
res.append([nums[i],nums[j],nums[left],nums[right]])
while left < right and nums[left] == nums[left+1]:
left += 1
while left < right and nums[right] == nums[right-1]:
right -= 1
left += 1
right -= 1
elif tmp > target:
right -= 1
else:
left += 1
return res
c++ y总版 【三重循环,本质是一样,过程写法区别】
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
for (int i = 0; i < nums.size(); i ++ ) {
if (i && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < nums.size(); j ++ ) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
for (int k = j + 1, u = nums.size() - 1; k < u; k ++ ) {
if (k > j + 1 && nums[k] == nums[k - 1]) continue;
while (u - 1 > k && nums[i] + nums[j] + nums[k] + nums[u - 1] >= target) u -- ;
if (nums[i] + nums[j] + nums[k] + nums[u] == target) {
res.push_back({nums[i], nums[j], nums[k], nums[u]});
}
}
}
}
return res;
}
};