[Leetcode] 3Sum

Source: Internet
Author: User

This was an extension of the 2Sum problem. The idea was pretty simple (even no need to use hash). Sort the array and then starting from the first element, set of pointers left and right: one after the Current element and the other at the end of the tail. If all the three elements sum to 0, then they is an answer. Add them to the result. Then your need to being careful to skip the duplicates! If you pay enough attention to the details, this problem have a fairly straightforward implementation without too many tric Ks.

The final code is as follows.

1vector<vector<int>> Threesum (vector<int>&nums) {2vector<vector<int> >Res;3         if(Nums.size () <=2)returnRes;4 sort (Nums.begin (), Nums.end ());5         intL =0, r = nums.size ()-1;6          for(inti =0; I < (int) Nums.size ()-2;) {7             intL = i +1, r = nums.size ()-1;8              while(L <r) {9                 if(Nums[i] + nums[l] + nums[r] = =0) {Tenvector<int> Ans (3); Oneans[0] =Nums[i]; Aans[1] =Nums[l]; -ans[2] =Nums[r]; - res.push_back (ans); the                      while(L < r && Nums[l] = = ans[0]) l++; -                      while(R > L && nums[r] = = ans[2]) r--; -                 } -                 Else if(Nums[i] + nums[l] + Nums[r] >0) r--; +                 Elsel++; -             } +i++; A              while(I < (int) nums.size () && nums[i-1] = = Nums[i]) i++; at         } -         returnRes; -}

[Leetcode] 3Sum

Contact Us

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.