15. 3Sum
- 头尾指针
题目
Given an array S of n integers, are there elements a, b, c in S 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.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路
- 简化思路
- 将三数相加求零的问题简化为target待定的两数和问题。
- 将数组排序,方便排重。
- 左右指针,在确定基础数字后,依序将最大数和最小数相加,减少无用的算术。
- 复杂性分析:
- 时间复杂度:O(n^2).
- 空间复杂度:O(n).(待确定)
题解
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int> > ret;
int len = nums.size();
if (len<3)
return ret;
sort(nums.begin(), nums.end());
for (int i = 0; i < len; i++) {
if (nums[i] > 0)
break;
if (i > 0 && nums[i] == nums[i-1])
continue;
int begin = i+1, end = len-1;
while (begin < end) {
int sum = nums[i] + nums[begin] + nums[end];
if (sum == 0) {
vector<int> t;
t.push_back(nums[i]);
t.push_back(nums[begin]);
t.push_back(nums[end]);
ret.push_back(t);
begin++;
end--;
while (begin < end && nums[begin] == nums[begin-1])
begin++;
while (begin < end && nums[end] == nums[end+1])
end--;
} else if (sum>0)
end--;
else
begin++;
}
}
return ret;
}
};