首页 技术 正文
技术 2022年11月15日
0 收藏 383 点赞 3,948 浏览 1144 个字

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

思路:先对vector进行排序,这样的话如果前两个数之和大于9,那么也就可以直接pass了

然后把vector中的数依次放入map中,暴力循环,每次计算前两个数之和,再在map中找到第三个数,存在一个set中,再把set存在一个set中,避免重复。

在不重复的情况下把这三个数放入vector中。

#include<iostream>
#include<vector>
#include<map>
#include<set>
#include <algorithm>
using namespace std;vector<vector<int>> threeSum(vector<int>& nums) {
map<int,int> temp;
vector<vector<int>> ans;
set<set<int>> anss;
int len = nums.size();
int n = ;
sort(nums.begin(), nums.end());
for (int i = ; i < len; i++)
{
temp[nums[i]] = i;
}
for (int i = ; i < len; i++){
for (int j = i+; j < len; j++)
{
int num = -nums[i] - nums[j];
if (num>) continue;
map<int, int> ::iterator add = temp.find(num);
if (add == temp.end() || add->second <= j) continue;
set<int> t;
t.insert(nums[i]);
t.insert(nums[j]);
t.insert(add->first);
//cout << nums[i] << nums[j] << add->first << endl;
if (anss.count(t) == )
{
anss.insert(t);
vector<int> t;
t.push_back(nums[i]);
t.push_back(nums[j]);
t.push_back(add->first);
ans.push_back(t);
cout << nums[i] << nums[j] << add->first << endl;
} }
}
return ans;
}int main(){
vector<int> a = { -, , , , -, - };
vector<vector<int>> ans = threeSum(a);
system("pause");
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,944
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,469
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,283
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,099
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,729
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,766