#include<iostream> #include <vector> #include <set> #include <functional> #include <stdlib.h> #include <stdio.h> #include <string> #include <sstream> #include <list> #include <map> #include <stack> #include <algorithm> //#include <iterator> using namespace std; #include <iostream> #include <string> using namespace std; vector<vector<int>> threeSum(vector<int>& nums) { int length = nums.size(); if (length < 3) return vector<vector<int>>(); int pa = 0, pb = 1, pc = length - 1; sort(nums.begin(), nums.end(), [](const int &a, const int &b){return a < b; }); vector<vector<int>> result; for (int pa = 0; pa < length - 2; pa++) { pb = pa + 1; pc = length - 1; int value = -nums[pa]; while (pb < pc) { if (nums[pb] + nums[pc] > value) pc--; else if (nums[pb] + nums[pc] < value) pb++; else { result.push_back({ nums[pa], nums[pb], nums[pc] }); while (nums[pb] == nums[pb+1]) pb++; while (nums[pc] == nums[pc - 1]) pc--; pb++; pc--; } } } sort(result.begin(), result.end()); auto end = unique(result.begin(), result.end()); result.erase(end, result.end()); return result; } //void unique(vector<vector<int>> &group) //{ // //} int main() { vector<int> vi = { -4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6 }; vector<vector<int>> result = threeSum(vi); for (auto v : result) { for (auto i : v) cout << i << " "; cout << endl; } return 0; }
正常需要o(n^3)复杂度,可采用先固定第一位,然后后两位用游标的方式,复杂度(n^2)