15. 3Sum
2018-01-11 09:41
162 查看
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.
of zero.
Note: 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: void Sum3_helper(vector<int> &nums,int begin,int end,int target,int first,vector<vector<int>> &result) { int low=begin,high=end; while(low<high) { if(high-low+1==2) { if(nums[low]+nums[high]==target) { vector<int> tmp; tmp.push_back(first); tmp.push_back(nums[low]); tmp.push_back(nums[high]); result.push_back(tmp); } return; } if(nums[low]+nums[high]>target) high--; else if(nums[low]+nums[high]<target) low++; else { if((low<end)&&(nums[low]==nums[low+1])) { low++; continue; } if (high>begin&&(nums[high]==nums[high-1])) { high--; continue; } vector<int> tmp; tmp.push_back(first); tmp.push_back(nums[low]); tmp.push_back(nums[high]); result.push_back(tmp); low++; } } } vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> result; if(nums.size()<3) return result; int target=0; sort(nums.begin(),nums.end()); for (int i=0; i<nums.size()-2;) { int t=target-nums[i]; Sum3_helper(nums, i+1, nums.size()-1, t,nums[i],result); int tmp=nums[i]; while(tmp==nums[i]&&i<nums.size()-2) i++; } return result; } };
相关文章推荐
- 【leetcode】15. 3sum
- 15. 3Sum
- (java)Leetcode-15. 3Sum
- Leetcode 15. 3Sum (Medium) (cpp)
- [LeetCode-Java]15. 3Sum
- leetcode 15. 3Sum 题解
- 15. 3Sum
- 15. 3Sum hash解法 vs 双指针解法
- 15. 3Sum
- [leetcode]15. 3Sum
- [leetcode]15. 3Sum(Java实现)
- 蜗牛慢慢爬 LeetCode 15. 3Sum [Difficulty: Medium]
- leetcode习题解答: 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- LeetCode——15. 3Sum
- leetcode15. 3Sum
- leetcode解题报告15. 3Sum