[Leetcode] [Python]18:4sum

Source: Internet
Author: User

#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '

18:4sum
https://oj.leetcode.com/problems/4sum/

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, a≤b≤c≤d)
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)

===comments by dabay===
The question of K sum can be converted to k-1 sum until 3 sum.
This problem can use space to change the time, with a hash table to record two numbers and the value of their coordinates.
Then two cycles, determine whether there is a hit value in the hash to meet and for target.
If there is, because two cycles are small to large, it should be to meet the size of the hash table smaller coordinates than the internal sequential coordinates.
‘‘‘
Class Solution:
# @return A list of lists of length 4, [[Val1,val2,val3,val4]]
def foursum (self, num, target):
D = {}
Num.sort ()
For i in xrange (Len (num)-1):
For j in Xrange (i+1, Len (num)):
sum2 = Num[i]+num[j]
If sum2 not in D:
D[SUM2] = [[I,j]]
Else
D[sum2].append ([i,j])

res = []
For i in xrange (Len (num)-3):
For j in Xrange (i+1, Len (num)-2):
x = target-(Num[i] + num[j])
If x in D:
for (M,n) in d[x]:
If M > J and [Num[i],num[j],num[m],num[n]] not in res:
Res.append ([num[i],num[j],num[m],num[n]])
return res


def main ():
Sol = solution ()
Nums = [-2,-1, 0, 0, 1, 2]
Print sol.foursum (nums, 0)


if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)

[Leetcode] [Python]18:4sum

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.