LeetCode 15 3Sum

来源:互联网 发布:数据分析师薪酬待遇 编辑:程序博客网 时间:2024/06/10 00:54

15. 3Sum

My Submissions
Total Accepted: 111041 Total Submissions: 595068 Difficulty: Medium

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

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

    For example, given array S = {-1 0 1 2 -1 -4},    A solution set is:    (-1, 0, 1)    (-1, -1, 2)

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss


在一个数组里找三个数,让其相加等于0

第一次裸O(n^3)暴力,妥妥超时了。

稍稍优化了一下,就能过了。


class Solution {public:    vector<vector<int>> threeSum(vector<int>& nums)    {        vector<vector<int>> ret;        sort(nums.begin(),nums.end());        for(int i=0;i<nums.size();i++)        {                if(i>0&&nums[i]==nums[i-1])                        continue;                for(int j=i+1;j<nums.size();j++)                {                        if(j>i+1&&nums[j]==nums[j-1])                                continue;                        for(int k=j+1;k<nums.size();k++)                        {                                if(k>j+1&&nums[k]==nums[k-1])                                        continue;                                if(nums[i]+nums[j]+nums[k]==0)                                {                                        vector<int> temp;                                        temp.push_back(nums[i]);                                        temp.push_back(nums[j]);                                        temp.push_back(nums[k]);                                        ret.push_back(temp);                                }                        }                }        }        return ret;    }};


0 0
原创粉丝点击