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]
]
分析
给定一个数组,返回数组中和等于0的三个元素。
首先想到的是暴力解决法,三层for循环,时间复杂度是O(n^3),并且还要处理重复的问题,显然不是题目想要的解法。如果对数组先进行排序,将时间复杂度降为O(nlgn).
先对数组进行排序,然后采用左右夹逼的方法,令target = 0,使三数之和等于0,最后将三个数输出即可。
C++实现:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
if(nums.size() < 3)
return result;
sort(nums.begin(),nums.end());
const int target = 0;
auto last = nums.end();
for (auto i = nums.begin();i < last - 2;++i){
auto j = i + 1;
if(i > nums.begin() && *i == *(i-1))
continue;
auto k = last - 1;
while(j < k){
if(*i + *j + *k < target){
++j;
while(*j == *(j - 1)&&j < k)
++j;
}
else if(*i + *j + *k > target){
--k;
while(*k == *(k+1)&&j < k)
--k;
}
else{
result.push_back({*i,*j,*k});
++j;
--k;
while(*j == *(j - 1)&&*k == *(k + 1)&& j < k)
++j;
}
}
}
return result;
}
};
python实现
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums.sort()
for i in xrange(0, len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
continue
target = 0 - nums[i]
start, end = i + 1, len(nums) - 1
while start < end:
if nums[start] + nums[end] > target:
end -= 1
elif nums[start] + nums[end] < target:
start += 1
else:
res.append((nums[i], nums[start], nums[end]))
end -= 1
start += 1
while start < end and nums[end] == nums[end + 1]:
end -= 1
while start < end and nums[start] == nums[start - 1]:
start += 1
return res