The Solution to LeetCode 15 3Sum
2017-03-09 16:57
411 查看
Question:
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: The solution set must not contain duplicate triplets.
这里的Note我在一开始想算法的时候没注意到,好像结果里边出现了重复的三个数,先贴上我的代码,不管啦!!这个改进问题留在下篇好了,警示自己先把题目读完,没读完就造成这种后果啦。
再说说思路吧,看到给出的例子,我就按照例子来想方法,思考过程的图片如下……
![](https://img-blog.csdn.net/20170309171441327?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY2hlbmdzajU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
Answer:
Run Code Result:
Your input
Your answer
Expected answer
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: The solution set must not contain duplicate triplets.
这里的Note我在一开始想算法的时候没注意到,好像结果里边出现了重复的三个数,先贴上我的代码,不管啦!!这个改进问题留在下篇好了,警示自己先把题目读完,没读完就造成这种后果啦。
再说说思路吧,看到给出的例子,我就按照例子来想方法,思考过程的图片如下……
Answer:
class Solution { public: vector<vector<int> >* r; vector<vector<int>> threeSum(vector<int>& nums) { r= new vector<vector<int>>(); if(nums.size()<3) { return *r; } sort(nums.begin(), nums.end()); int i=0; int j=1; int p=2; for (i=0,j=1;j<nums.size()-1;i++,j++) { for(p=2;p<nums.size();p++) { if(nums[i]+nums[j]+nums[p]==0) { vector<int> tmp; tmp.push_back(nums[i]); tmp.push_back(nums[j]); tmp.push_back(nums[p]); r->push_back(tmp); } } } return *r; } };
Run Code Result:
Your input
[-1,0,1,2,-1,-4]
Your answer
[[-1,-1,2],[-1,0,1],[0,1,-1]]
Expected answer
[[-1,-1,2],[-1,0,1]]
相关文章推荐
- The Solution to LeetCode 15 3Sum改进版
- The Solution to Leetcode 136 Single Number
- Leetcode 13. Roman to Integer The Solution of Python
- The Solution to Leetcode 463 Island Perimeter
- The Solution to Leetcode 110 Balanced Binary Tree
- The Solution to LeetCode 111 Minimum Depth of Binary Tree
- The Solution to LeetCode 120 Triangle
- The Solution to Leetcode 101 Symmetric Tree
- The Solution to Leetcode 520 Detect Capital
- The Solution to Leetcode 118 Pascal's Triangle
- The Solution to Leetcode 344 Reverse String
- The Solution to Leetcode 563 Binary Tree Tilt
- The Solution to LeetCode 147 Insertion Sort List
- Leetcode 8. String to Integer (atoi) The Solution of Python
- The Solution to Leetcode 617 Merge Two Binary Trees
- The Solution to Leetcode 268 Missing Number
- The Solution to Leetcode 119 Pascal's Triangle II
- Leetcode 12. Integer to Roman The Solution of Python
- The Solution to Leetcode 137 Single Number II
- The Solution to Leetcode 35 Search Insert Position