[Leetcode] 15. 3Sum 解题报告
2016-12-12 10:46
239 查看
题目:
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.
思路:
对于3Sum而言,即使原数组是排好序的,也需要至少O(n^2)的时间复杂度。而排序的时间复杂度是O(nlogn),不影响最终的时间复杂度,所以我们可以首先对数组进行排序,然后采用双指针扫描的方法实现第二层循环。整个算法的时间复杂度就是O(n^2),空间复杂度为O(1)。
为了防止出现重复结果,需要注意一旦相邻元素相同,则后续元素应该跳过。详见下面代码的注释部分。另外一种简单方法是,将nums转存到一个set<int>中,然后在set<int>中完成两遍扫描。这样做的好处在于set不仅可以自动排序,而且可以自动去重。
代码:
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.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
思路:
对于3Sum而言,即使原数组是排好序的,也需要至少O(n^2)的时间复杂度。而排序的时间复杂度是O(nlogn),不影响最终的时间复杂度,所以我们可以首先对数组进行排序,然后采用双指针扫描的方法实现第二层循环。整个算法的时间复杂度就是O(n^2),空间复杂度为O(1)。
为了防止出现重复结果,需要注意一旦相邻元素相同,则后续元素应该跳过。详见下面代码的注释部分。另外一种简单方法是,将nums转存到一个set<int>中,然后在set<int>中完成两遍扫描。这样做的好处在于set不仅可以自动排序,而且可以自动去重。
代码:
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> ret; if(nums.size() < 3) return ret; sort(nums.begin(), nums.end()); long previous = LONG_MAX; // make sure previous is not equal to any element for(int i = 0; i < nums.size() - 2; ++i) { int target = - nums[i]; if(target == previous) // make sure the first element is not duplicate continue; int j = i + 1; int k = nums.size() - 1; while(j < k) { if(nums[j] + nums[k] == target) { ret.push_back(vector<int>{nums[i], nums[j], nums[k]}); while(j < k && nums[j] == nums[j+1]) // make sure the second element is 4000 not duplicate j++; while(j < k && nums[k] == nums[k-1]) // make sure the third element is not duplicate k--; j++; k--; } else if(nums[j] + nums[k] < target) { j++; } else { k--; } } previous = target; } return ret; } };
相关文章推荐
- [leetcode] 15. 3Sum 解题报告
- LeetCode解题报告—— Container With Most Water & 3Sum Closest & Letter Combinations of a Phone Number
- [LeetCode 解题报告]016. 3Sum Closest
- LeetCode 解题报告 3Sum Closest
- leetcode解题报告16. 3Sum Closest
- [LeetCode] 3Sum 解题报告
- LeetCode解题报告—— 1-bit and 2-bit Characters & 132 Pattern & 3Sum
- leetcode解题报告15. 3Sum
- LeetCode解题报告--2Sum, 3Sum, 4Sum, K Sum求和问题总结
- LeetCode解题报告--2Sum, 3Sum, 4Sum, K Sum求和问题总结
- [LeetCode 解题报告]015. 3Sum
- leetcode解题之 15. 3Sum Java版(结果为目标值的三个数字)
- [leetcode] 259. 3Sum Smaller 解题报告
- 3Sum LeetCode 解题报告
- [Leetcode] 259. 3Sum Smaller 解题报告
- [LeetCode]3Sum,解题报告
- Leetcode #15 3Sum 三数之和 解题小节
- 【LeetCode】3Sum 解题报告
- [Leetcode] 319. Bulb Switcher 解题报告
- Leetcode 119. Pascal's Triangle II 杨辉三角2 解题报告