Leetcode 15. 3Sum

Poby’s Home
1 min readJun 19, 2022

--

O(n^2) loop and two pointers

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:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(begin(nums), end(nums));
vector<vector<int>> ans;
for (int i=0; i<nums.size() && nums[i] <= 0; i++) {
if (i == 0 || nums[i-1] != nums[i]) {
twoSumII(nums, i, ans);
}
}
return ans;
}
void twoSumII(vector<int>& nums, int i, vector<vector<int>> &res) {
int lo = i+1;
int high = nums.size() - 1;
while (lo < high) {
int sum = nums[i] + nums[lo] + nums[high];
if (sum < 0) {
lo++;
} else if (sum > 0) {
high--;
}else {
res.push_back({nums[i], nums[lo], nums[high]});
lo++;
high--;
while(high > 0 && nums[high] == nums[high+1]){
high--;
}
}
}
}
};

--

--

No responses yet