Leetcode: 15. 3Sum

Description

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.

Example

For example, given array S = [-1, 0, 1, 2, -1, -4],

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

思路

  • 找出三个数的和0的所有情况。
  • 先排序
  • 然后从前往后找 两个数的和是另外一个的负数。
  • 注意区分重复情况。即一个数若已经找过了,那下一次出现重复时应该跳过。
  • 这个题扎心了,一年前提交还是67ms,现在149ms,还是最好的一次情况。难道一年不见,大神们都成长这么快了吗

代码

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        
        int len = nums.size();
        if(len <= 2) return res;
        
        int index1 = 0, index2 = 0;
        int i = 0 , s, e;
        sort(nums.begin(), nums.end());
        
        for(i = 0; i < len; ++i){
            if(i > 0 && nums[i] == nums[i - 1]) continue;
            
            s = i + 1;
            e = len - 1;
            
            while(s < e){
                if(s > i + 1 && nums[s] == nums[s - 1]){
                    s++;
                    continue;
                } 
                if(e < len - 1 && nums[e] == nums[e + 1]){ 
                    e--;
                    continue;
                }
            
                if(nums[s] + nums[e] > -nums[i]) e--;
                else if(nums[s] + nums[e] < -nums[i]) s++;
                else {
                    vector<int> tmp;
                    tmp.push_back(nums[i]);
                    tmp.push_back(nums[s]);
                    tmp.push_back(nums[e]);
                    res.push_back(tmp);
                    s++;
                }
            }
        }
        
        return res;
    }
};
原文地址:https://www.cnblogs.com/lengender-12/p/6821219.html