Skip to content

Commit 7f90e7e

Browse files
author
He Hao
committed
add solution to problem 923
1 parent 31fa3da commit 7f90e7e

File tree

1 file changed

+31
-0
lines changed
  • leetcode_python_solutions

1 file changed

+31
-0
lines changed

leetcode_python_solutions/923.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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

0 commit comments

Comments
 (0)