018 4Sum

018 4Sum

感觉最差的情况应该是O(n*n*n)的复杂度

from collections import defaultdict
class Solution:
    # @param {integer[]} nums
    # @param {integer} target
    # @return {integer[][]}
    def fourSum(self, nums, target):
        dic = defaultdict(list)
        d = {}
        nums.sort()
        ans = []
        #minCom = nums[0] + nums[1]
        for i in xrange(0, len(nums)):
            for j in xrange(i + 1, len(nums)):
                s = nums[i] + nums[j]
                dic[s].append([nums[i], nums[j], i, j])
        for v in dic:
            if v > target/2:
                continue
            if target - v in dic:
                for x in dic[v]:
                    for  y in dic[target - v]:
                        if x[3] < y[2]:
                            tmp = [x[0],x[1],y[0],y[1]]
                            t = (x[0],x[1],y[0],y[1])
                            if t not in d:
                                ans.append(tmp)
                                d[t] = 0
        return ans

 

posted @ 2015-08-10 12:51  dapanshe  阅读(112)  评论(0编辑  收藏  举报