Given an array S ofn 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] ] 从头开始遍历,i为数组第一个的值,pre为数组第二个的值,back为数组的第三个的值,主要是以向中靠拢的原则。 还有就是由于不是每个元素是独一的,要遍历相同的元素。class Solution { public: vector > threeSum(vector & nums) { vector > t; sort(nums.begin(), nums.end()); int len = nums.size(); for (int i = 0; i x(3, 0); x[0] = nums[i]; x[1] = nums[pre]; x[2] = nums[back]; t.push_back(x); while (pre < back && nums[pre] == x[1]) pre++; //当对于i来说,第二个元素的值只能用一次 while (pre< back && nums[back] == x[2]) back--;//当对于i来说,第三个元素的值只能用一次 } else if (nums[i] + s2 > 0){ back--; } else if (nums[i] + s2 < 0){ pre++; } } while (i + 1 < len && nums[i + 1] == nums[i]) //第二个元素和第一个元素相同时,下回就不能将第二个元素当作第一个元素来遍历 i++; } return t; } };