您的位置:首页 > 其它

【Leetcode】4Sum

2014-03-17 22:35 274 查看
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:

Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)

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)


class Solution {
public:
vector<vector<int>> fourSum(vector<int>& num, int target) {
vector<vector<int>> result;
if (num.size() < 4) return result;
sort(num.begin(), num.end());
auto last = num.end();
for (auto a = num.begin(); a < prev(last, 3); ++a) {
if (a != num.begin() && *a == *prev(a)) continue;
for (auto b = next(a); b < prev(last, 2); ++b) {
if (b != next(a) && *b == *prev(b)) continue;
auto c = next(b);
auto d = prev(last);
while (c < d) {
int sum = *a + *b + *c + *d;
if (sum < target) {
++c;
} else if (sum > target) {
--d;
} else {
result.push_back({*a, *b, *c, *d});
++c, --d;
}
}
}
}
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
};


View Code
与前面的题类似,先排序再夹逼,但是需要循环两次。O(n3).

其它的方法:hash_map缓存两两元素的和。

C++11的写法好别扭...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: