leetcode 4sum python
class Solution(object): def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ numLen=len(nums) if numLen <= 3: return list() nums.sort() res,d=set(),{} for p in xrange(numLen): q=p+1 while q < 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)) q+=1 for i in xrange(numLen): j=i+1 while j < numLen-2: tmp = target-nums[i]-nums[j] if tmp in d: for k in d[tmp]: if k[0] > j: res.add( ( nums[i], nums[j], nums[k[0]], nums[k[1]] ) ) j+=1 return [list(i) for i in res]
@link http://chaoren.is-programmer.com/posts/45308.html