Leetcode#18 4 Sum

Source: Internet
Author: User

Problem Definition:

Given an array S of n integers, is there elements a, b, C, and D in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

    • Elements in a quadruplet (a,b,c,D) must is in non-descending order. (ie, abcd)
    • The solution set must not contain duplicate quadruplets.
    For example, given array S = {1 0-1 0-2 2}, and target = 0.    A solution set is:    ( -1,  0, 0, 1)    ( -2,-1, 1, 2)    ( -2,  0, 0, 2)

Solution:

1) The most direct idea, fixed the first number, becomes 3 sum problem, then becomes 2 sum problem; This idea can be extended to k-sum. The problem of repeating tuples is avoided by skipping repeating elements.

1     #@param {integer[]} nums2     #@param {integer} target3     #@return {integer[][]}4     deffoursum (Nums, target):5 Nums.sort ()6res=[]7first=08Finalfirst=len (nums)-49Finalsecond=len (nums)-3TenRightbound=len (nums)-1 One          whilefirst<=Finalfirst: Anf=Nums[first] -Second=first+1 -              whilesecond<=Finalsecond: theLeft=second+1 -right=Rightbound -ns=Nums[second] -                  whileleft<Right : +Nl=Nums[left] -Nr=Nums[right] +four=nf+ns+nl+nr A                     ifFour>Target: atRight-=1 -                     eliffour<Target: -Left+=1 -                     Else: -res+=[NF, NS, NL, nr], -                          whileLeft<right andnums[left]==nl: inLeft+=1 -                          whileLeft<right andnums[right]==NR: toRight-=1 +Second+=1 -                  whileSecond<=finalsecond andnums[second]==NS: theSecond+=1 *First+=1 $              whileFirst<=finalfirst andnums[first]==NF:Panax NotoginsengFirst+=1 -         returnRes

2) HashTable. Element 22 in the array is summed, and as key, the corresponding value is an array of multiple four tuples, each of which holds the two elements for key and their subscripts. O (n^2) time forms this table.

Then traverse Hashtable [O (N)], and for Key1, find the Key2 [O (1)] that can add the target, and combine the four tuples in the value corresponding to the two keys. Preventing duplication is key. You can use Set (set) to store these intersecting tuples.

1     #@param {integer[]} nums2     #@param {integer} target3     #@return {integer[][]}4     deffoursum (self, Nums, target):5n=Len (nums)6         ifN<4:7             return []8vsmap={}     9res=[]Ten          forIinchrange (n): One              forJinchRange (i+1, N): Akey=nums[i]+Nums[j] - Vsmap.setdefault (key, []) - vsmap[key].append ([nums[i], I, Nums[j], j]) the          forKeyinchVsmap: -need=target-Key -             ifNeedinchVsmap: -pb=Vsmap[need] +             Else: -                 Continue +Pa=Vsmap[key] A              forAinchPA: at                  forBinchPB: -                     ifA[1]==B[1]orA[3]==B[3]orA[1]==B[3]orA[3]==b[1]: -                         Continue -Cmb=sorted ([a[0], a[2], b[0], b[2]]) -                     ifCmb not inchRes: -res+=CMB, in         returnRes

Leetcode#18 4 Sum

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.