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] ]
分析
遍历每一个nums[i], 把它当作 twoSum 的 target number。 39ms
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | class Solution { public : vector<vector< int >> threeSum(vector< int >& nums) { int len = nums.size(); vector<vector< int >> result; if ( len < 3) return result; sort(nums.begin(), nums.end()); for ( int i = 0; i < len - 2; i++){ if ( i > 0 && nums[i] == nums [ i - 1]) continue ; /** cut edge to accelerate the speed **/ if ( nums[i] + nums[i + 1] + nums[i + 2] > 0) break ; if ( nums[i] + nums[len - 2] + nums[ len - 1] < 0) continue ; int l = i + 1, r = len - 1; while ( l < r){ int sum = nums[i] + nums[l] + nums[r]; if ( sum < 0) l++; else if ( sum > 0) r--; else { result.push_back(vector< int >{nums[i], nums[l], nums[r]}); /** cut edge to accelerate the speed **/ l++;r--; while (l < r && nums[l] == nums[l - 1])l++; while (l < r && nums[r] == nums[r + 1])r--; } } } return result; } }; |