您的位置:首页 > 其它

算法分析与设计——LeetCode Problem.18 4Sum

2017-12-28 22:58 429 查看
题目链接

问题描述

Given an array S of n integers, are there elements a, b, c, and d in S 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.
For example, given array S = [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]
]


解题思路

还是跟Leetcode15题 3Sum类似,这题也是先对数组排序,然后确定两个数,将确定的第二个数的后一个数作为头指针位置,数组最后一个数为尾指针位置。

但是这题可能会出现四个数组成的vector中的所有元素相同的情况,为了解决这个问题,可以考虑先用set来存储vector,最后再把set中的vector转到vector中。

代码如下

class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int leng = nums.size();
vector<vector<int>> myFourSum;

set<vector<int>> saveSum;

if (leng < 4) return myFourSum;
sort(nums.begin(), nums.end());
for (int i = 0; i < leng - 3; i++) {
for (int j = i + 1; j < leng - 2; j++) {
int left = j + 1, right = leng - 1;
while (left < right) {
if (target == nums[i] + nums[j] + nums[left] + nums[right]) {
vector<int> vec;
vec.push_back(nums[i]);
vec.push_back(nums[j]);
vec.push_back(nums[left]);
vec.push_back(nums[right]);
//myFourSum.push_back(vec);
saveSum.insert(vec);
left++;
right--;
while (left < right && nums[left] == nums[left - 1]) left++;
while (left < right && nums[right] == nums[right + 1]) right--;
//at this time might variable j and the variable next to it might be equal
}
if (target > nums[i] + nums[j] + nums[left] + nums[right]) {
left++;
continue;
}
if (target < nums[i] + nums[j] + nums[left] + nums[right]) {
right--;
continue;
}
}
}
}
set<vector<int>>::iterator it = saveSum.begin();
for (; it != saveSum.end(); it++) {
myFourSum.push_back(*it);
}

return myFourSum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: