传送门:题目
题解:
暴力做,先把序列sort一遍,然后,设三个指针(l,m,r)(左中右),l从[1:len-2)遍历,然后m从i+1处开始遍历,同时r从len-1处开始遍历。现在的时间复杂度O(
log2n+n2
l
o
g
2
n
+
n
2
)
如果不设三指针,就三个for循环,扫一遍就好,这样的时间复杂度O(
n3
n
3
)
AC代码:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
int l, m, r, len, sum;
len = nums.size();
sort(nums.begin(), nums.end());
for (l = 0; l < len - 2 && nums[l] <= 0; l++) {
if (l > 0 && nums[l] == nums[l - 1]){
continue;
}
m = l + 1, r = len - 1;
while (m < r) {
sum = nums[l] + nums[m]+ nums[r];
if (sum == 0)
ans.push_back({nums[l], nums[m], nums[r]});
if (sum <= 0) {
m++;
while (nums[m - 1] == nums[m] && m < r)
m++;
}
if (sum >= 0) {
r--;
while (nums[r + 1] == nums[r] && m < r)
r--;
}
}
}
return ans;
}
};