classSolution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() ret = [] used = {} tmp = {} n = len(nums) for i in range(n): if nums[i] not in tmp: tmp[nums[i]] = [] tmp[nums[i]].append(i)
for i in range(n): for j in range(i+1, n): key = (str(nums[i]) + "_" + str(nums[j])) if key in used: continue used[key] = 1 need = 0 - (nums[i] + nums[j]) if need < nums[j]: continue if need not in tmp: continue for k in tmp[need]: if k == i or k == j: continue ret.append((nums[i], nums[j], nums[k])) break return ret
for i inrange(n): for j inrange(i+1, n): s = nums[i] + nums[j] two_sum[s].append((i, j))
ret = [] used = {} for i inrange(n): need = 0 - nums[i] for (a, b) in two_sum[need]: if a == i or b == i: continue tmp = [nums[i], nums[a], nums[b]] tmp.sort() key = "_".join(map(str, tmp)) if key in used: continue used[key] = 1 ret.append((nums[i], nums[a], nums[b])) return ret