寻找数组中三个数求和为0的组合(naive edition)
来源:互联网 发布:画图软件如何使用方法 编辑:程序博客网 时间:2024/06/06 03:27
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:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
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)
#include<iostream>#include<string>#include<vector>#include<algorithm>using namespace std;class solution{public:vector<vector<int>> ress;vector<int> res;vector<vector<int> > sum_3(vector<int>& nums){for (int i = 0; i < nums.size()-2; i++){for (int j = i+1; j < nums.size()-1; j++){for (int k = j+1; k < nums.size(); k++){if (nums[i] + nums[j] + nums[k] == 0){res.clear();res.push_back(nums[i]);res.push_back(nums[j]);res.push_back(nums[k]);sort(res.begin(),res.end());//用了algotithm中的sort()方法进行排序ress.push_back(res);}}}}return ress;}};int main(){vector<int> a = { 0, 1, -1, 2, -2, 3, -1, 5, -8, 9, 45 };solution s;vector<vector<int>> ress;ress=s.sum_3(a);for (int i = 0; i < ress.size(); i++){sort(ress.begin(),ress.end());//可以对向量的向量(二维数组)排序,首先比较的是各个向量的第一个元素//若第一个一样大,则比较第二个,以此排序ress.erase((unique(ress.begin(), ress.end())),ress.end());//可以对向量或这个向量的向量的执行这些操作for (int j = 0; j < 3; j++){cout << ress[i][j] << ' ';}cout << endl;}}
阅读全文
0 0
- 寻找数组中三个数求和为0的组合(naive edition)
- 求一个数组中三个数和为0的组合
- 寻找数组中两个数的和为M的组合
- 寻找数组中满足和为定值的两个数或所有可能组合
- 一个数组中寻找所有三个符合条件的数
- 找出求和为0的三个数 3sum
- 在数组中,求和为定值的元素组合
- 给定一个无序整形数组,找出其中所以三个数之和为0的所有组合
- C++寻找数组元素组合之和为给定数
- 数据结构与算法[LeetCode]—3Sum 求数组中和为0 的三个数的组合
- 求数组内任意三个数相加和为零的组合
- 第十四题(升序数组中寻找和为特定数的两个元素)
- 从数组中找出所有组合为s的数
- 输出数组中所有三个数相加为0的解
- 输出数组中所有三个数相加为0的解
- [LeetCode]—3Sum Closest 求数组中三个数之和最接近给定target的组合
- 常见面试算法题:给定数组中寻找加和为特定数的两个数
- 寻找丢失的三个数
- HTML中name和id的区别(转载)
- MySQL_函数、排序、分组
- GitHub, Kubernetes因何结缘 ?
- Git版本控制之多人协作
- Java并发编程实战(三)结构化并发应用程序
- 寻找数组中三个数求和为0的组合(naive edition)
- 一部电影,一种人生 (会议分享表述用)
- 深度学习
- 11.存储空间优化
- 判断一个单项链表中是否有环
- python 报错函数
- Linux中VNC的安装与配置
- POJ 3009 Curling 2.0(dfs)
- java注解的使用