本文主要是介绍LeetCode OJ:3Sum,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
3Sum
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)
class Solution {
public:vector<vector<int> > threeSum(vector<int> &num) {sort(num.begin(),num.end());vector<vector<int>> ans;vector<int> res;int n=num.size();for(int i=0;i<n;){for(int p1=i+1,p2=n-1;p1<p2;){int sum=num[i]+num[p1]+num[p2];if(sum==0){res.clear();res.push_back(num[i]);res.push_back(num[p1]);res.push_back(num[p2]);ans.push_back(res);int t=num[p1];while(p1<p2&&num[p1]==t)++p1;}else if(sum < 0)p1++;else p2--;}int t=num[i];while(i<n&&num[i]==t)++i;}return ans;}
};
这篇关于LeetCode OJ:3Sum的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!