1. 程式人生 > >leetcode18 四數之和

leetcode18 四數之和

def fourSum(nums, target):
    numLen, res, d = len(nums), set(), {}
    if numLen < 4: return []
    nums.sort()
    '''
    二層迴圈遍歷任意兩個元素對和存放到字典d裡並把序號存起來
    '''
    for p in range(numLen):
        for q in range(p + 1, numLen):
            if nums[p] + nums[q] not in d:
                d[nums[p] + nums[q]] = [(p, q)]
            else:
                d[nums[p] + nums[q]].append((p, q))
    '''
    二層迴圈遍歷如果target-任意兩數之和的差存在字典中遍歷符合的字典的values值,滿足條件的就可以放到結果集中。
    '''
    for i in range(numLen):
        for j in range(i + 1, numLen - 2):
            T = target - nums[i] - nums[j]
            if T in d:
                for k in d[T]:
                    if k[0] > j: res.add((nums[i], nums[j], nums[k[0]], nums[k[1]]))
    print([list(i) for i in res])
    return [list(i) for i in res]