Table of contents
1. Question analysis
Question link: 15. Sum of three numbers - Leetcode
The question is to find non-repeating triples whose sum is 0.
Note that each element of the triple has a different position, so what does it mean to not repeat?
We can look at the first example,
He found three triples, but he only returned two,
That is, triples with the same elements are considered the same triplet. (If not, the empty set is returned.)
2. Algorithm principle
The first idea is of course brute force enumeration, specifically,
Sort first, then violently enumerate, and finally use set to remove duplicates.
Then we have to think about how to optimize N3’s violent enumeration.
After sorting, there is an ordered array, then we have to think about whether to use binary or double pointers for optimization: of course, double pointers are given priority.
Let’s look at the specific solution:
Fix an i position:
We only need to quickly find the position where the sum of left position + right position is 4 through double pointers.
3. Code writing
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size() - 2; i++) {
int left = i + 1, right = nums.size() - 1;
while(left < right) {
int sum = nums[i] + nums[left] + nums[right];
if(sum < 0) left++;
else if(sum > 0) right--;
else { // sum == 0
ans.push_back({nums[i], nums[left], nums[right]});
while(left < right && nums[left] == nums[left + 1]) left++;
while(left < right && nums[right] == nums[right - 1]) right--;
left++, right--;
}
}
while(i < nums.size() - 2 && nums[i] == nums[i + 1]) i++;
}
return ans;
}
};
Write at the end:
The above is the content of this article, thank you for reading.
If you feel that you have gained something, you can give the blogger a like .
If there are omissions or mistakes in the content of the article, please private message the blogger or point it out in the comment area~