【leetcode】3Sum (medium)
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
思路:
把最小值从头到尾循环,中间值和最大值两边收缩。
我写的时候是在最后去重复,总是超时。后来看了人家的答案,发现可以每次对最小、中间、最大值去重。就可以AC了
#include <iostream> #include <vector> #include <algorithm> #include <queue> #include <stack> using namespace std; class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> > ans; if(num.size() < 3) { return ans; } int small = 0; int big = num.size() - 1; int mid = 0; int sum = 0; sort(num.begin(), num.end()); for(small = 0; small < num.size() - 2; /*small++*/) //最小数字循环 中间与最大数字两边收缩 { mid = small + 1; big = num.size() - 1; while(mid < big) { sum = num[small] + num[mid] + num[big]; if(sum > 0) { big--; } else if(sum < 0) { mid++; } else { vector<int> v; v.push_back(num[small]); v.push_back(num[mid]); v.push_back(num[big]); ans.push_back(v); do { mid++; }while (mid < big && num[mid - 1] == num[mid]); //注意!! do { big--; }while (mid < big && num[big + 1] == num[big]);//注意!! } } do{ small++; }while (small < num.size() - 1 && num[small - 1] == num[small]);//注意!! } return ans; } }; int main() { Solution s; vector<int> num; num.push_back(-4); num.push_back(-1); num.push_back(-1); num.push_back(-1); num.push_back(-1); num.push_back(0); num.push_back(0); num.push_back(0); num.push_back(1); num.push_back(2); vector<vector<int>> ans = s.threeSum(num); return 0; }