#Leetcode# 15. 3Sum

https://leetcode.com/problems/3sum/

Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

代码:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int n = nums.size();
        sort(nums.begin(), nums.end());
        set<vector<int>> ans;
        if(nums.empty() || nums[0] > 0 || nums[n - 1] < 0) return {};
        for(int i = 0; i < n; i ++) {
            if(nums[i] > 0) break;
            int target = 0 - nums[i];
            int l = i + 1, r = n - 1;
            while(l < r) {
                if(nums[l] + nums[r] == target) {
                    ans.insert({nums[i], nums[l], nums[r]});
                    
                    while(l < r && nums[l] == nums[l + 1]) l ++;
                    while(l < r && nums[r] == nums[r - 1]) r --;
                    
                    l ++;
                    r --;
                }
                else if(nums[l] + nums[r] < target) l ++;
                else r --;
            }
        }
        return vector<vector<int>>(ans.begin(), ans.end());
    }
};

 

先排序 如果最小的数字就大于零或者最大的数字小于零那一定不满足要求 剪枝 用 $set$ 去重 先找到一个之后用双指针找另外两个值 时间复杂度为 $O(n ^ 2)$ 

昨天晚上写了无数个 WA 和 TLE 时间复杂度是 $O(n ^ 2 * logn)$ 等我改对了再贴上来吧

原文地址:https://www.cnblogs.com/zlrrrr/p/10005838.html