原题地址:https://leetcode-cn.com/problems/3sum/description/
题目描述:
给定一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ]
解题方法:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
int n = nums.size();
sort(nums.begin(), nums.end()); //排序,从小到大
for(int i = 0 ; i < n - 2; i ++){
int j = i + 1;
int k = n - 1;
while(j < k){
if(nums[i] + nums[j] + nums[k] > 0){
k --;
}
else if(nums[i] + nums[j] + nums[k] < 0){
j ++;
}
else{
ans.push_back({nums[i], nums[j], nums[k]});
while(nums[j+1] == nums[j]) j++;
j ++;
}
}
while(nums[i+1] == nums[i]) i++;
}
return ans;
}
};
时间复杂度为O(N^2)。
首先使用sort()函数进行排序,注意函数里的参数。利用头尾两指针进行遍历,判断三数之和是否为零。
使用vector的push_back()函数添加成员,注意写法,含有{}。