15.3Sum (Two-Pointers)
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:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
思路:首先大循环第一个数,从第一个数之后首尾指针向中间夹逼,时间复杂度O(n2)。需要注意跳过重复的数字。
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { int size = nums.size(); if(size < 3) return result; sort(nums.begin(), nums.end()); find(nums, 1, size-1, -nums[0]); for(int i = 1; i < size-2; i++){ if(nums[i]!=nums[i-1]) find(nums, i+1, size-1, -nums[i]); } return result; } void find(vector<int>& nums, int start, int end, int target){ int sum; while(start<end){ sum = nums[start]+nums[end]; if(sum == target){ item.clear(); item.push_back(-target); item.push_back(nums[start]); item.push_back(nums[end]); result.push_back(item); do{ start++; }while(start!= end && nums[start] == nums[start-1]); do{ end--; }while(end!=start && nums[end] == nums[end+1]); } else if(sum>target){ do{ end--; }while(end!=start && nums[end] == nums[end+1]); } else{ do{ start++; }while(start!= end && nums[start] == nums[start-1]); } } } private: vector<vector<int>> result; vector<int> item; };