Skip to content

Instantly share code, notes, and snippets.

@liketheflower
Created December 11, 2019 17:01
Show Gist options
  • Save liketheflower/404bd130727f609452d1d1a243a4f2b5 to your computer and use it in GitHub Desktop.
Save liketheflower/404bd130727f609452d1d1a243a4f2b5 to your computer and use it in GitHub Desktop.
class Solution:
def threeSumMulti(self, A: List[int], target: int) -> int:
cnt = collections.Counter(A)
res, MOD =0, 10**9+7
seen = set()
for a, b in itertools.combinations(cnt.keys(), 2):
c = target - a - b
a, b, c = sorted([a,b,c])
if (a, b, c) not in seen:
seen.add((a,b,c))
if len(set([a, b, c])) == 3:
res += cnt[a]*cnt[b]*cnt[c] % MOD
else:
if a==b:
res += (cnt[a]*(cnt[a]-1)//2)*cnt[c] % MOD
else:#b==c
res += (cnt[b]*(cnt[b]-1)//2)*cnt[a] % MOD
# a==b==c
if target%3==0:
a = target//3
res += (cnt[a]*(cnt[a]-1)*(cnt[a]-2))//6
return res%MOD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment