4sum

problem description:

this is the addition about the 3sum,you can use the method of solve the 3sum.

given a integer and the target,you should return the unique integer inclued four nums about a+b+c+d = traget

for example:

list = [1,2,3,4,5,6] target= 7

return 

[[1,6],[2,5],[3,4]]

 

there is my python soultion:

it just expand the 3sum solution

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        length = len(nums)
        nums.sort()
        if length < 4:
            return []
        else:
            returnlist = []
            for i in range(length-3):
                if i != 0 and nums[i] == nums[i-1]:
                    continue
                temptarget = target- nums[i]
                for j in range(i+1,length-2):
                    if j!=i+1 and nums[j] == nums[j-1]:
                        continue
                    k,l = j+1, length-1
                    while k<l:
                        sums = nums[j]+nums[k]+nums[l]
                        if sums > temptarget or ( l < length-1 and nums[l] == nums[l+1]):
                            l -= 1
                        elif sums < temptarget or (k > j+1 and nums[k] == nums[k -1]) :
                            k += 1
                        else:
                            returnlist.append([nums[i], nums[j], nums[k],nums[l]])
                            k += 1
                            l -= 1
                       
            return returnlist

 

posted @ 2017-04-18 09:55  whatyouknow123  阅读(122)  评论(0编辑  收藏  举报