数据结构与算法[LeetCode]—3Sum 求数组中和为0 的三个数的组合
2014-06-25 21:16
363 查看
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.
思路:直接分别进行三次遍历复杂度为)O(n^3)。
如果我们进行排序,那么最后一个值采用二分搜索那么可以降低最后一个数查找的复杂度。总体复杂度为O(n^2logn)
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)
思路:直接分别进行三次遍历复杂度为)O(n^3)。
如果我们进行排序,那么最后一个值采用二分搜索那么可以降低最后一个数查找的复杂度。总体复杂度为O(n^2logn)
#include<iostream> #include<algorithm> #include<vector> using namespace std; //先排序,后依次两两组合遍历 class Solution{ public: vector<vector<int> > threeSum(vector<int>& num){ vector<vector<int> > result; if(num.size()<3)return result; sort(num.begin(),num.end()); const int target=0; vector<int>::iterator last=num.end(); for(vector<int>::iterator a=num.begin();a<(last-2);a=upper_bound(a,last-2,*a)){ for(vector<int>::iterator b=a+1;b<(last-1);b=upper_bound(b,last-1,*b)){ int c=target-*b-*a; if(binary_search(b+1,last,c)){ vector<int> vec; vec.push_back(*a); vec.push_back(*b); vec.push_back(c); result.push_back(vec); } } } return result; } };
相关文章推荐
- [LeetCode]—3Sum Closest 求数组中三个数之和最接近给定target的组合
- 找出数组中和为N+1的的所有组合
- 求数组中和为给定数所有的组合
- LeetCode-3SUM(数组中三数之和为0)及其 closest
- 算法题:求指定数组中和为N的出现的所有组合(二)
- 算法题:求一个数组中和为sum的所有组合
- 阿里巴巴笔试题--求数组中和为给定数所有的组合
- [leetcode 46] Permutations------数组中元素的所有排列组合集合
- LeetCode-3Sum -三数求和-有序数组扫描
- LeetCode | 3Sum(三个数的和等于0)
- [LeetCode]1. 2Sum 数组中和为特定值的两个数
- 找出数组中和为10的元素的组合
- 数据结构与算法[LeetCode]—数组中出现次数异与其他数的一个数
- leetcode:3Sum (三个数的和)
- [LeetCode] 3Sum 找出所有三个元素之和为0的组合
- 第二十一题(求数组中和为特定数的所有组合)
- 求数组中和为给定数所有的组合
- 数组中和为N的组合
- 数据结构与算法[LeetCode]—找出N个节点的BST的所有形态组合
- LeetCode 15 3Sum 找出数组里面3个数的和等于指定值。