题目:给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] (若两个四元组元素一一对应,则认为两个四元组重复):
0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。
示例 1:输入:nums = [1,0,-1,0,-2,2], target = 0 输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2: 输入:nums = [2,2,2,2,2], target = 8 输出:[[2,2,2,2]]
思路:四数之和可以在三数之和上做修改,三数之和通过双指针解法可以将时间复杂度降到O(n2),四数之和通过双指针解法可以将时间复杂度降到O(n3),也就是降一个数量级。但是要注意四数之和与target比较大小时,很有可能会发生数据溢出,所以要做修改。
四数之和代码:
class Solution { //四数之和
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
if (nums.size() < 4)
return result;
for (int first = 0; first < nums.size(); first++) {
if (first > 0 && nums[first] == nums[first - 1])
continue;
for (int second = first + 1; second < nums.size(); second++) {
if (second > first + 1 && nums[second] == nums[second - 1])
continue;
int third = second + 1;
int four = nums.size() - 1;
while (third < four){
//if (nums[first] + nums[second] + nums[third] + nums[four] > target) { //会溢出
if (nums[first] + nums[second] > target - (nums[third] + nums[four])) {
four--;
while (third < four && nums[four] == nums[four + 1])
four--;
}
else if (nums[first] + nums[second] < target - (nums[third] + nums[four])) {
third++;
while (third < four && nums[third] == nums[third - 1])
third++;
}
else {
result.push_back(vector<int>{nums[first], nums[second], nums[third], nums[four]});
while (third < four && nums[four] == nums[four - 1])
four--;
while (third < four && nums[third] == nums[third + 1])
third++;
third++;
four--;
}
}
}
}
return result;
}
};
int main()
{
vector<int> nums = { 2, 2, 2, 2, 2 };
int target = 8;
Solution solution;
solution.fourSum(nums, target);
return 0;
}
本文介绍了如何使用双指针优化算法解决LeetCode中的四数之和问题,针对数组 nums 和目标值 target,找到满足 nums[a] + nums[b] + nums[c] + nums[d] = target 的不重复四元组解。通过示例和代码实现展示了如何避免数据溢出,降低时间复杂度至 O(n^3)。
824

被折叠的 条评论
为什么被折叠?



