[leetcode]15. 3Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w5688414/article/details/86531279

Description

Given an array nums of n integers, are there elements a, b, c 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]
]

分析

  • 这个题目的解法我觉得是个经典的解法,先排序,然后再遍历暴力找出来。
  • 由于题目给出不能含有重复项,我们很容易想到用set集合来做,最后变成vector就行了。

代码

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> result;
        if(nums.size()<3){
            return result;
        }
        set<vector<int>> temp;
        sort(nums.begin(),nums.end());
        for(int i=0;i<nums.size()-2;i++){
            int left=i+1;
            int right=nums.size()-1;
            while(left<right){
                int sum=nums[left]+nums[right]+nums[i];
                if(sum==0){
                    vector<int> ans={nums[i],nums[left],nums[right]};
                    temp.insert(ans);
                    left++;
                    right--;
                }else if(sum<0){
                    left++;
                }else{
                    right--;
                }
            }
        }
        return vector<vector<int>> (temp.begin(),temp.end());
    }
};

参考文献

[编程题]3sum

猜你喜欢

转载自blog.csdn.net/w5688414/article/details/86531279