来源:力扣(LeetCode)
链接: https://leetcode.cn/problems/3sum
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
python实现
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
# 暴力,三重循环
n = len(nums)
if n < 3:
return []
res = []
for i in range(n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
if nums[i] + nums[j] + nums[k] == 0:
if sorted([nums[i], nums[j], nums[k]]) not in res:
res.append(sorted([nums[i], nums[j], nums[k]]))
return res
c++实现
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
vector <vector <int>> res;
if (n<3)
return {};
for (int i=0; i<n-2; i++){
for (int j=i+1; j<n-1; j++){
for (int k=j+1; k<n; k++){
if (nums[i] + nums[j] + nums[k] == 0)
{
vector<int> inner_res = {nums[i], nums[j], nums[k]};
sort(inner_res.begin(), inner_res.end());
if (find(res.begin(), res.end(), inner_res) == res.end()){
res.push_back(inner_res);
}
}
}
}
}
return res;
}
};
复杂度分析
排序虽然也花时间,但可以忽略不计
python实现
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
# 转换为两数之和 利用并利用哈希表的方法
n = len(nums)
hashTable = dict()
res = []
if n < 3:
return res
for i in range(n):
if nums[i] in hashTable:
hashTable[nums[i]].append(i)
else:
hashTable[nums[i]] = [i]
for i in range(n-1):
for j in range(i+1, n):
diff = 0 - nums[i] - nums[j]
if diff in hashTable:
# 这个地方要判断是否有重复元素
diff_index = hashTable[diff]
if len(diff_index) == 1 and diff_index[0] not in [i, j]:
inner_res = sorted([nums[i], nums[j], diff])
if inner_res not in res:
res.append(inner_res)
elif len(diff_index) > 1:
for index in diff_index:
if index not in [i, j]:
inner_res = sorted([nums[i], nums[j], nums[index]])
if inner_res not in res:
res.append(inner_res)
return res
c++实现
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
// 两层循环+哈希表
int n = nums.size();
unordered_map <int, vector <int>> hashTabel;
if (n<3){
return {};
}
vector <vector <int>> res;
for (int i=0; i<n; i++){
auto it = hashTabel.find(nums[i]);
if (it != hashTabel.end()){
// find
hashTabel[nums[i]].push_back(i);
}
else{
hashTabel[nums[i]] = {i};
}
}
for (int i=0; i<n-1; i++){
for (int j=i+1; j<n; j++)
{
int diff = 0 - nums[i] - nums[j];
auto it = hashTabel.find(diff);
if (it != hashTabel.end()){
if (it->second.size() == 1){
int index = it->second.front();
if(index != i && index != j){
vector <int> inner_res = {nums[i], nums[j], diff};
sort(inner_res.begin(), inner_res.end());
auto it2 = find(res.begin(), res.end(), inner_res);
if(it2 == res.end()){
res.push_back(inner_res);
}
}
}
else if (it->second.size() > 1){
int n2 = it->second.size();
for (int k=0; k<n2; k++){
if (it->second[k] != i && it->second[k] != j){
vector <int> inner_res = {nums[i], nums[j], nums[it->second[k]]};
sort(inner_res.begin(), inner_res.end());
auto it2 = find(res.begin(), res.end(), inner_res);
if (it2 == res.end()){
res.push_back(inner_res);
}
}
}
}
}
}
}
return res;
}
};
复杂度分析
两重循环+哈希表元素中的遍历循环
哈希表
python实现
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
# 排序 + 双指针 + 三数判相邻元素重复
n = len(nums)
if n < 3:
return []
nums.sort()
res = []
for index in range(n-2):
if nums[index] > 0:
break
if index > 0 and nums[index] == nums[index-1]:
continue
left = index + 1
right = n - 1
while left < right:
if nums[index] + nums[left] + nums[right] == 0:
res.append([nums[index], nums[left], nums[right]])
left += 1
right -= 1
while nums[left] == nums[left-1] and left < right:
left += 1
while nums[right] == nums[right+1] and left < right:
right -= 1
elif nums[index] + nums[left] + nums[right] > 0:
# right -> move left
right -= 1
elif nums[index] + nums[left] + nums[right] < 0:
# left -> move right
left += 1
return res
c++实现
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
// 排序加左右双指针+while去重
int n = nums.size();
if (n<3){
return {};
}
vector <vector <int>> res;
sort(nums.begin(), nums.end());
for (int i=0; i<n-2; i++)
{
if (nums[i] > 0){
break;
}
if (i>0 && nums[i] == nums[i-1]){
continue;
}
int left = i + 1;
int right = n - 1;
while (left < right){
if (nums[i] + nums[left] + nums[right] == 0){
res.push_back({nums[i], nums[left], nums[right]});
left++;
right--;
while (nums[left] == nums[left-1] && left < right){
left++;
}
while (nums[right] == nums[right+1] && left < right){
right--;
}
}
else if (nums[i] + nums[left] + nums[right] > 0){
right--;
}
else {
left++;
}
}
}
return res;
}
};
复杂度分析
for循环+left<while循环, 排序耗时O(nlogn)
总的耗时是O(n^2)
排序消耗的空间,存储空间是O(1)