Given an array nums
of n integers, are there elements a, b, c in nums
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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
直接暴力搜索的时间复杂度为$O(N^3)$.
思路:借鉴两数和的思想,先将数组排序,然后双指针。
1 class Solution { 2 public: 3 vector<vector<int>> threeSum(vector<int>& nums) { 4 if (nums.size() <= 2) 5 return {}; 6 std::sort(nums.begin(), nums.end()); 7 vector<vector<int>> res; 8 for (int i = 0; i < nums.size() - 2; i++) { 9 if (nums[i] > 0) continue; //排好序,如果nums[i]>0,那么后面的两个数加起来不可能小于0 10 if ((i > 0) && (nums[i] == nums[i - 1])) continue; 11 int li = i + 1, ri = nums.size() - 1, sum = -nums[i]; 12 while (li < ri) { 13 if (nums[li] + nums[ri] == sum) { 14 res.push_back({nums[i], nums[li], nums[ri]}); 15 while (li < ri && (nums[li + 1] == nums[li])) li++; 16 while (li < ri && (nums[ri] == nums[ri - 1])) ri--; 17 li++; 18 ri--; 19 } else if (nums[li] + nums[ri] < sum) { 20 li++; 21 } else { 22 ri--; 23 } 24 } 25 } 26 return res; 27 } 28 };