File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
leetcode_python_solutions Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ def threeSumMulti (self , arr : List [int ], target : int ) -> int :
3+ arr .sort ()
4+ ans = 0
5+ MOD = 10 ** 9 + 7
6+ for i in range (len (arr )):
7+ new_sum = target - arr [i ]
8+ left , right = i + 1 , len (arr )- 1
9+ while left < right :
10+ if arr [left ] + arr [right ] < new_sum :
11+ left += 1
12+ elif arr [left ] + arr [right ] > new_sum :
13+ right -= 1
14+ else :
15+ if arr [left ] == arr [right ]:
16+ ans += (right - left + 1 )* (right - left )// 2
17+ ans %= MOD
18+ break
19+ else :
20+ n_left = n_right = 1
21+ while left < right and arr [left ] == arr [left + 1 ]:
22+ left += 1
23+ n_left += 1
24+ while left < right and arr [right ] == arr [right - 1 ]:
25+ right -= 1
26+ n_right += 1
27+ ans += n_left * n_right
28+ ans %= MOD
29+ left += 1
30+ right -= 1
31+ return ans
You can’t perform that action at this time.
0 commit comments