15. 3Sum
题目描述
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
示例:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
解答
这道题如果上来直接暴力破解的话,时间复杂度为O( n 3 n^3 n3)。
一个想法是,先把数组排序一遍(O( n l o g n nlogn nlogn)),然后固定第一个数,其他两个数用两个指针(two pointer)的方法来做,总时间复杂度为O( n 2 n^2 n2)。
注意这道题要求不能有重复的值,所以每找到一组解,我们要确保这组解之前没有出现过。
假设三个数的下标是 i, j, k
因为数组是排好序了,所以在找到一组解之后,我们令j++, k– 直到j, k的值和之前不同。
最后别忘了要保证i的值和上一次循环不同。
代码
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
for (int i = 0; i < nums.size(); i++) {
auto target = - nums[i];
int j = i + 1;
int k = nums.size() - 1;
while (j < k) {
if (nums[j] + nums[k] == target) {
res.push_back({nums[i], nums[j], nums[k]});
while(j < k && nums[j] == nums[j + 1]) j++;
while(k > j && nums[k] == nums[k - 1] ) k--;
j++;
k--;
}
else if (nums[j] + nums[k] < target) {
j++;
}
else {
k--;
}
}
while (i + 1 < nums.size() && nums[i] == nums[i + 1]) i++;
}
return res;
}
};