# Leetcode (3Sum)

Source: Internet
Author: User

Topic

Given an array S of n integers, is 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.

Note:
Elements in a triplet (A,B,C) must is 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)``
Analysis

The sequence of three of the sum of 0 in a given integer sequence is calculated!

I used a violent solution, three-layer loop, but Status:time Limit exceeded~~~
We haven't figured out a more efficient code.

Time Limit exceeded code
``classSolution { Public: vector<vector<int>>Threesum ( vector<int>& Nums) { vector<vector<int>>vvintSize = Nums.size ();if(Size <3)returnvv for(inti =0; i < size; i++) { for(intj = i +1; J < size; J + +) { for(intK = j +1; K < size; k++) {if(Nums[i] + nums[j] + nums[k] = =0)                    {intarr[3] = {Nums[i], nums[j], nums[k]};//Sort the elements in arr from small to largeSort (arr); vector<int>v = {arr, arr +3};if(!find (vv, v)) Vv.push_back (v); }Else{Continue; }                }//for}//for}//for        returnvv }BOOLFind vector<vector<int>>&AMP;VV, vector<int>&AMP;V) { vector<vector<int>>:: Iterator iter; for(iter = Vv.begin (); ITER! = Vv.end (); iter++) {if((*iter) [0] = = v[0] && (*iter) [1] = = v[1] && (*iter) [2] = = v[2])            {return true; }                               }return false; }voidSortint*a) { for(inti =0; I <3; i++) { for(intj =0; J <3I1; J + +) {if(A[j] > a[j +1])                {intt = a[j]; A[J] = a[j +1]; A[j +1] = t; }            }        }    }};``
AC Code

Waiting to be added ~ ~

Leetcode (3Sum)

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.