题目:
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> threeSum(vector & nums) { vector > 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