3sum

Posted HUSTLX

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3sum相关的知识,希望对你有一定的参考价值。

#include <string>
#include <stack>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
vector<vector<int>> threeSum(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    int len = nums.size();
    vector<vector<int>> res;
    for (int i = 0; i < len; i++) {
        int sum = 0 - nums[i];
        int low = i + 1;
        int high = len - 1;
        while (low < high) {
            if (sum > nums[low] + nums[high]) low++;
            else if (sum < nums[low] + nums[high]) high--;
            else {
                vector<int> temp = { nums[i],nums[low],nums[high] };
                res.push_back(temp);
                while (low < high &&nums[low] == temp[1]) low++;
                while (low < high && nums[high] == temp[2]) high--;
            }
        }
        while ((i + 1 < len) && nums[i] == nums[i + 1]) i++;
    }
    return res;
}

int main() {
    vector<int> nums = {-1,-1,0,1 };
    vector<vector<int>> re=threeSum(nums);
}

以上是关于3sum的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] 3Sum

3Sum

15. 3Sum

3sum

3Sum Closest

15. 3Sum