LEETCODE ALGORITHM:15. 3Sum

题目

    • Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

      Notice that the solution set must not contain duplicate triplets.

      Example 1:

      1
      2
      Input: nums = [-1,0,1,2,-1,-4]
      Output: [[-1,-1,2],[-1,0,1]]

      Example 2:

      1
      2
      Input: nums = []
      Output: []

      Example 3:

      1
      2
      Input: nums = [0]
      Output: []

      Constraints:

      • 0 <= nums.length <= 3000
      • -105 <= nums[i] <= 105

题解

i,j,k分别代表排序后数组里三个数的索引号

因为要避免重复,一样的数组不要,所以如果任何一个位置前后两次选择的数一致就要跳过

第三个数的指针倒叙来找

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 n=nums.size();
if(n==0) return {};
vector<vector<int>> ans;
sort(nums.begin(),nums.end());
for(int i=0;i<n;i++){
if(i>0 && nums[i]==nums[i-1]){
continue;
}
int target= -nums[i];
int k=n-1;
for(int j=i+1;j<n;j++){
if(nums[i]>0) break;
if(j>i+1 && nums[j]==nums[j-1]){
continue;
}
while(j<k && nums[j]+nums[k] > target){
k--;
}
if(j==k) break;
if(nums[j]+nums[k]==target){
ans.push_back(vector<int>{nums[i],nums[j],nums[k]});
}
}
}
return ans;
}
};