# [Leetcode] [Javascript]3sum

Source: Internet
Author: User

3Sum

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, abc)
• 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)`

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

At first I thought of the violent triple loop, suggesting that double pointers.

To sort first, the solution of the problem depends on the order.

The outer loop loops from beginning to end, with double pointers to the inner layer.

Each round of the inner layer adds the value of the two pointers to the outer loop, if the equality is found, if it is less than 0, the head pointer goes backward, and the pointer is greater than 0. It is possible to do so based on an already sequenced order.

`1 /**2 * @param {number[]} nums3 * @return {number[][]}4  */5 varThreesum =function(nums) {6     varres = [];7Nums =nums.sort (sorting);8 9      for(vari = 0; i < nums.length-2; i++){Ten         if(Nums[i-1]!== undefined && nums[i-1] = = =Nums[i]) { One             Continue; A         } -         varCurr =Nums[i]; -         varm = i + 1; the         varn = nums.length-1; -          while(M <N) { -             if(Nums[m] + nums[n] + Curr = = 0){ - Res.push ([Curr, Nums[m], Nums[n]]); +                  while(M < n && nums[m] = = = Nums[m + 1]){ -m++; +                 } A                  while(M < n && nums[n] = = = Nums[n-1]){ atn--; -                 } -m++; n--;  -}Else if(Nums[m] + nums[n] + Curr > 0){ -n--; -}Else { inm++; -             } to         } +     } -     returnRes; the  *     functionsorting (A, b) { \$         if(A >b) {Panax Notoginseng             return1; -}Else if(A <b) { the             return-1; +}Else{ A             return0; the         } +     } -};`

[Leetcode] [Javascript]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.