标签:
题目:
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] ]
这题比较麻烦的点在于如何忽略重复元素的影响。首先将元素排序,然后从最左边开始,如果有三个元素相加为0,那么就把这三个数push进结果res里,然后排除重复元素。如果a+b+c的和大于0,那么从右边缩小范围,如果小于0,从左边缩小范围。
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> res; if (nums.size()<3) return res; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size() - 2; i++){ if (i > 0 && nums[i] == nums[i-1])continue; int a = nums[i]; int left = i+1; int right = nums.size()-1; while(left<right){ int b = nums[left]; int c = nums[right]; if ((a+b+c) == 0) { res.push_back(vector<int>{a,b,c}); while((left < nums.size()) && (nums[left] == b))left++; while((right >= 0) && (nums[right] == c))right--; } else if ((a+b+c)>0) right--; else left++; } } return res; } };
标签:
原文地址:http://www.cnblogs.com/Doctengineer/p/5813974.html