题目:15. 3Sum
Difficulty : Medium
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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
题意:
给出一个数列,输出数列中任意三个数之和为0 的所有组合。
分析:
- 所给数列为无序数列,因此先按正序排列。
- 数列中存在重复元素,因此 去重 保留唯一不重复元素。
- 遍历每一个元素,然后使用两数求和的思路就可以简化问题了。
- 由于C++使用unique会导致执行时间加长,因此可在排序后 对重复出现的非第一个元素直接忽略掉,从而节省一定的时间。
- 实现见下。
Code & C++
class Solution{
vector<vector<int>> threeSum(vector<int> &nums){
bool valid = True;
vector<vector<int>> ans;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();++i){
int total = -nums[i];
int front = i+1, end=nums.size()-1;
while(front<back){
int sum = nums[front] + nums[back];
if(sum<total){
++front;
}else if(sum>total){
--back;
}else{
vector<int> tmp = {nums[i], nums[front], nums[back]};
ans.push_back(tmp);
while(front<back && nums[front]==tmp[1])++front;
while(front<back && nums[back]==tmp[2])--back;
}
}
// 过滤掉重复的元素
while(i<nums.size()-1 && nums[i] == nums[i+1])++i;
}
return ans;
}
};
结果:
Runtime: 104 ms, faster than 100.00% of C++ online submissions for 3Sum.
Memory Usage: 17.6 MB, less than 46.29% of C++ online submissions for 3Sum.
Code & Python
class Solution:
def threeSum(self, nums: 'List[int]') -> 'List[List[int]]':
slen = len(nums)
if slen<3:return []
nums.sort()
ans = []
i=0
while i<slen:
front, back = i+1, slen-1
total = -nums[i]
while front < back:
sum = nums[front] + nums[back]
if sum<total:
front+=1
elif sum>total:
back-=1
else:
tmp = [nums[i],nums[front],nums[back]]
ans.append(tmp)
while front < back and nums[front]==tmp[1]: front+=1
while front < back and nums[back] ==tmp[2]: back-=1
i+=1
while i<slen and nums[i-1]==nums[i]:i+=1
return ans
结果:
Runtime: 664 ms, faster than 93.68% of Python3 online submissions for 3Sum.
Memory Usage: 16 MB, less than 80.64% of Python3 online submissions for 3Sum.
Status:ACCEPTED